我想在选中复选框时禁用某些行的可见性(折叠),并且该行上的绑定数据符合特定条件。例如(伪代码):
If(IsHideEnabledChecked && Row.Data.Enabled)
Row.Visibility = Collapsed
由于我正在处理的项目的性质,我已经以编程方式创建了数据网格,数据网格的数量需要与我的集合中的对象数量相匹配。通常在非wpf世界中,您将遍历网格并在条件下更改行:
public void HideEnabled(object sender, RoutedEventArgs)
Foreach(DataGrid grid in DataGrids)
{
Foreach(DataGridRow row in grid)
{
if(row[0].Value == True)
row.Visibile = false
}
}
我的问题是,如何在选中复选框后隐藏行?以及如何根据当前行的值检查?这一切都可以在c#中完成吗?我环顾四周,可以看到dataTriggers可用于将控件绑定到列和数据类型,但不包括检查绑定数据(属性"已启用")
非常感谢任何帮助:)
答案 0 :(得分:0)
你应该将你要隐藏的控件绑定到checkbox.IsChecked
这将为你提供一个可见性绑定的布尔值,你可以使用BooleanToVisibilityConverter转换我建议使用DataTemplate和Collection Binding而不是而不是代码,但你也可以在代码中执行此操作
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</UserControl.Resources>
<Checkbox x:Name="hider" />
<Control Visibility="{Binding IsChecked, Converter={StaticResource BooleanToVisibilityConverter}, ElementName=hider}" />
或者如果要将复选框与其他值结合使用,您可以创建自己的处理多个值的转换器,请参阅MultiValueConverter
public class MultiBooleanToVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.OfType<bool>().All(b => b == true))// your logic here
return Visibility.Visible;
else
return Visibility.Collapsed;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new InvalidOperationException("One Way only");
}
}
然后使用
<Control.Visibility>
<MultiBinding Converter="{StaticResource MultiBooleanToVisibilityConverter}">
<Binding Path="IsChecked" ElementName="hider"/>
<Binding Path="secondfield" />
</MultiBinding>
</Control.Visibility>
答案 1 :(得分:0)
您可以使用以下帮助方法处理Checked
的{{1}}事件并在可视树中找到其父CheckBox
容器:
DataGridRow
您只需像往常一样挂钩 private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
CheckBox checkBox = sender as CheckBox;
var dataObject = checkBox.DataContext as YourDataClass;
if (dataObject.SomeProperty == true)
{
DataGridRow parentRow = FindParent<DataGridRow>(checkBox);
if (parentRow != null)
parentRow.Visibility = Visibility.Collapsed;
}
}
private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null) return null;
var parentT = parent as T;
return parentT ?? FindParent<T>(parent);
}
事件的事件处理程序。在XAML标记中:
Checked
或以编程方式:
<CheckBox ... Checked="CheckBox_Checked" />