如何有条件地隐藏 WPF DataGrid 的 TemplateColumn 中的元素?
上下文:一个带有数据网格的 C# 4.0 WPF 应用程序,其中有一个显示进度条的 TemplateColumn。
如何让网格根据条件仅显示某些项目的进度条?
也许监听事件并隐藏单元格/将visibile 设置为 false 将是一种选择。
这是它现在的样子(所有项目都显示进度条):
<UserControl.Resources>
<DataTemplate x:Key="PotentialDataTemplate">
<Grid Width="70">
<ProgressBar
Height="12"
VerticalAlignment="Center"
Value="{Binding Path=Potential, Mode=OneWay}" />
</Grid>
</DataTemplate>
</UserControl.Resources>
<DataGrid x:Name="dataGrid"
ItemsSource="{Binding Path=Items}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn
Header="{Binding Source={x:Static text:TextBindingProvider.Instance}, Path=CompendiumHeaderPotential}"
Width="Auto"
MinWidth="80"
CellTemplate="{StaticResource PotentialDataTemplate}"
IsReadOnly="true"
SortMemberPath="Potential" />
</DataGrid.Columns>
</DataGrid>
Context: a C# 4.0 WPF application with a datagrid that has one TemplateColumn showing a progress bar.
How can one get the grid to only display the progress bar for certain items based on a condition?
Maybe listening to the events and hiding the cells / setting visibile to false would be an option.
This is how it looks right now (the progress bar is shown for all items):
<UserControl.Resources>
<DataTemplate x:Key="PotentialDataTemplate">
<Grid Width="70">
<ProgressBar
Height="12"
VerticalAlignment="Center"
Value="{Binding Path=Potential, Mode=OneWay}" />
</Grid>
</DataTemplate>
</UserControl.Resources>
<DataGrid x:Name="dataGrid"
ItemsSource="{Binding Path=Items}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn
Header="{Binding Source={x:Static text:TextBindingProvider.Instance}, Path=CompendiumHeaderPotential}"
Width="Auto"
MinWidth="80"
CellTemplate="{StaticResource PotentialDataTemplate}"
IsReadOnly="true"
SortMemberPath="Potential" />
</DataGrid.Columns>
</DataGrid>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据可见性的条件,您有多种选择。如果您有一个单独的属性,例如“IsPotentialVisible”,那么您可以使用 BooleanToVisibilityConverter 将其绑定到进度条的 Visibility 属性。
接下来,如果它是一个简单的条件,例如“当 Potential == 0 时隐藏”,那么您可以创建一个处理此条件的 DataTrigger。
否则,您还可以创建一个自定义转换器,根据所需的任何输入属性/参数输出可见性。
You have a couple of options depending on what the conditions are for visibility. If you have a separate property such as "IsPotentialVisible" then you can bind this to the Visibility property of the progressbar using a BooleanToVisibilityConverter.
Next up, if it is a simple condition such as "hide when Potential == 0", then you could create a DataTrigger that handles this condition.
Otherwise you can also create a custom converter that spits out a visibility based on whatever input properties / parameters are required.
刚刚找到答案,我只需添加 Visibility 属性并将其绑定到 ViewModel 中的某些条件逻辑。
所以:
Just found an answer, I simply add the Visibility attribute and Bind it to some conditional Logic in the ViewModel.
So: