我目前正在尝试让我的第一个 WPF 用户控件正常工作。它由一些 UI 元素和一个 ViewModel 组成,用于保存数据并完成工作。它有一个项目列表作为输入,另一个项目列表作为输出。当绑定到输入的列表发生变化时,我需要在 ViewModel 中完成某个任务。但我找不到在更改此列表时运行方法的方法。
我认为最好的方法是为输入和输出列表设置 2 个 DependencyProperties。如果输出列表发生变化,则应通知绑定对象,因为它已注册为 DependencyProperty。我想使用 DependencyPropertyChanged 委托来指定 ViewModel 中要在输入更改时执行的方法。
public List<AClass> Input
{
get { return (List<AClass>)GetValue(InputProperty); }
set { SetValue(InputProperty, value); }
}
public static readonly DependencyProperty InputProperty =
DependencyProperty.Register("Input", typeof(List<AClass>), typeof(MyUserControl), new UIPropertyMetadata(new List<AClass>(),CallBackDelegate));
我尝试了不同的方法在视图模型构造函数中设置委托,但它们都不起作用。如何在我的视图模型中指定一个方法来在输入列表更改时执行?
Im currently trying to get my first WPF Usercontrol to work. It consists of some UI elements and a ViewModel, holding the data and doing the work. It has a List of items as input, and another List of items as output. I need a certain task in my ViewModel to be done, when the list bound to the input changes. But i can't find a way to run a method at change of this List.
I thought the best way is to have 2 DependencyProperties for the input and output list. If the output list changes, the bound objects should be informed as it is registered as DependencyProperty. And i wanted to use the DependencyPropertyChanged delegate to specify the method in my ViewModel to execute on Input change.
public List<AClass> Input
{
get { return (List<AClass>)GetValue(InputProperty); }
set { SetValue(InputProperty, value); }
}
public static readonly DependencyProperty InputProperty =
DependencyProperty.Register("Input", typeof(List<AClass>), typeof(MyUserControl), new UIPropertyMetadata(new List<AClass>(),CallBackDelegate));
I tried different approaches to set the delegate in the viewmodel constructor, but they all did not work. How can I specify a method within my viewmodel to execute on change of input List?
发布评论
评论(1)
我将使用 ObservableCollections,而不是 DependencyProperty 中的列表。这会为您提供“自动”通知等。这里是我头脑中可能不太完整的伪代码,可以帮助您入门:
ViewModel
控制/视图中的某处
控制/查看隐藏代码
Instead of lists in a DependencyProperty, I would use ObservableCollections. That gives you "automatic" notifications, etc. Here is outta-my-head-probably-not-quite-complete pseudo code to get you started:
ViewModel
Somewhere in Control/View
Control/View Code-Behind