我有依赖属性选择项的用户控件(这是枚举值的集合)
public IEnumerable SelectedItems
{
get { return (IEnumerable)GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems", typeof(IEnumerable),
typeof(UserControl1), new FrameworkPropertyMetadata(OnChangeSelectedItems)
{
BindsTwoWayByDefault = true
});
private static void OnChangeSelectedItems(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var uc = d as UserControl1;
if (uc != null)
{
var oldObservable = e.OldValue as INotifyCollectionChanged;
var newObservable = e.NewValue as INotifyCollectionChanged;
if (oldObservable != null)
{
oldObservable.CollectionChanged -= uc.SelectedItemsContentChanged;
}
if (newObservable != null)
{
newObservable.CollectionChanged += uc.SelectedItemsContentChanged;
uc.UpdateMultiSelectControl();
}
}
}
private void SelectedItemsContentChanged(object d, NotifyCollectionChangedEventArgs e)
{
UpdateMultiSelectControl();
}
我已使用转换器
将selectedItems依赖项属性与我的用户控件中的复选框绑定在一起<ItemsControl ItemsSource="{Binding Items}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<CheckBox x:Name="ChkBox" Margin="13 0 0 10" Content="{Binding}" >
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource CheckBoxConverter}" Mode="TwoWay" >
<Binding ElementName="ChkBox" Path="Content" />
<Binding RelativeSource="{RelativeSource FindAncestor,AncestorType={x:Type UserControl}}" Path="DataContext.SelectedItems" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay"></Binding>
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
和转换器
public class CheckBoxConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
if (values != null && values.Length > 1)
{
var content = values[0];
var selected = values[1] as IList;
if (selected != null && selected.Contains(content))
{
return true;
}
}
return false;
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter, System.Globalization.CultureInfo culture)
{
return new[] { Binding.DoNothing, Binding.DoNothing };
}
}
我的问题是,如果我在构建时添加了选定项目中的值,则转换器被调用但如果我在按钮上添加值,则不会被调用。可以告诉我其发生的原因以及我如何可以纠正这个。
答案 0 :(得分:2)
只有当您绑定的任何属性发生更改时,才会调用转换器的Convert
方法。您绑定了Content
的{{1}}属性和CheckBox
的{{1}}属性。当您向集合中添加新项目时,这些都不会更改。
尝试也绑定到集合的SelectedItems
属性:
UserControl