我的 WPF 应用程序中显示了两个集合,我希望其中一个的元素在另一个中被禁用。为此,我正在创建一个继承 ListBox 的自定义控件 FilteringListBox,并且我想在其中添加一些处理以禁用通过 FilteringListBox 上的属性在集合集中设置的元素。现在,我的问题是没有设置采用我想从中过滤元素的 ObservableCollection 的依赖属性——即使我在 xaml 中绑定(bind)到它。
我创建了一个简化的应用程序来重现该问题。这是我的 Xaml:
<StackPanel>
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical">
<TextBlock>Included</TextBlock>
<ListBox x:Name="IncludedFooList" ItemsSource="{Binding IncludedFoos}"></ListBox>
</StackPanel>
<Button Margin="10" Click="Button_Click">Add selected</Button>
<StackPanel Orientation="Vertical">
<TextBlock>Available</TextBlock>
<Listbox:FilteringListBox x:Name="AvailableFooList" ItemsSource="{Binding AvailableFoos}" FilteringCollection="{Binding IncludedFoos}"></Listbox:FilteringListBox>
</StackPanel>
</StackPanel>
</StackPanel>
这是我的自定义组件 - 当前仅包含依赖属性:
public class FilteringListBox : ListBox
{
public static readonly DependencyProperty FilteringCollectionProperty =
DependencyProperty.Register("FilteringCollection", typeof(ObservableCollection<Foo>), typeof(FilteringListBox));
public ObservableCollection<Foo> FilteringCollection
{
get
{
return (ObservableCollection<Foo>)GetValue(FilteringCollectionProperty);
}
set
{
SetValue(FilteringCollectionProperty, value);
}
}
}
完整的代码背后的代码和类定义在这里:
public partial class MainWindow : Window
{
private MainViewModel _vm;
public MainWindow()
{
InitializeComponent();
_vm = new MainViewModel();
DataContext = _vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (AvailableFooList.SelectedItem == null)
return;
var selectedFoo = AvailableFooList.SelectedItem as Foo;
_vm.IncludedFoos.Add(selectedFoo);
}
}
public class MainViewModel
{
public MainViewModel()
{
IncludedFoos = new ObservableCollection<Foo>();
AvailableFoos = new ObservableCollection<Foo>();
GenerateAvailableFoos();
}
private void GenerateAvailableFoos()
{
AvailableFoos.Add(new Foo { Text = "Number1" });
AvailableFoos.Add(new Foo { Text = "Number2" });
AvailableFoos.Add(new Foo { Text = "Number3" });
AvailableFoos.Add(new Foo { Text = "Number4" });
}
public ObservableCollection<Foo> IncludedFoos { get; set; }
public ObservableCollection<Foo> AvailableFoos { get; set; }
}
public class Foo
{
public string Text { get; set; }
public override string ToString()
{
return Text;
}
}
我在 FilteringListBox 中的 DependencyProperty FilteringCollection 的 setter 和 getter 中添加了断点,但它从未被触发。为什么?我该如何解决?
最佳答案
绑定(bind)系统绕过依赖属性的设置和获取访问器。如果您想在依赖属性更改时执行代码,您应该将 PropertyChangedCallback
添加到 DependencyProperty
定义中。
关于.net - 为什么在绑定(bind)到它时没有设置我的依赖属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3668196/