我在 wpf 中创建了一个用户控件,它由一个文本框和一个 ListView 组成。现在,我想将一个类对象绑定(bind)到我将使用此控件的表单中的 ListView 。所以,基本上我想动态设置 ListView 的绑定(bind)。
这可能很简单,但我是 wpf 的新手,这对我来说是一项艰巨的任务。请为此提出解决方案。
最佳答案
您需要将您的 ListView
的 ItemsSource
属性绑定(bind)到您的类实例的集合(为此我建议使用 ObservableCollection)。例如,您可以将集合放入 ListView
的 DataContext
中。然后绑定(bind)将只是
<ListView ItemsSource={Binding} .../>
创建一个类来包含此集合以及您的 UserControl
可能需要的任何其他对象并将此类的实例传递给 UserControl
会更有用数据上下文
。这是指MVVM模式。
编辑
您可以在代码隐藏或 xaml 中设置 DataContext。假设我们有一个包含集合的类:
public class ViewModel
{
public ViewModel()
{
Products = new ObservableCollection<Product>()
{
new Product("book"),
new Product("chair"),
new Product("table"),
new Product("bookshelf"),
}
}
ObservableCollection<Product> Products { get; set; }
}
下面是如何在代码中设置 UserControl 的 DataContext:
userControl.DataContext = new ViewModel();
其中 userControl 是您的 UserControl 的一个实例。
这是在 xaml 中的操作方法:
<UserControl ...
xmlns:vm="namespace_containing_class_ViewModel">
<UserControl.DataContext>
<!-- Following line instantiates the ViewModel class and calls its parameterless constructor -->
<vm:ViewModel />
</UserControl.DataContext>
...
<ListView ItemsSource="{Binding Products}"/>
...
</UserControl>
两种变体做完全相同的事情。请注意,ItemsSource="{Binding Products}"
表示 Binding.Path
属性设置为“Products”,并且将在 ListView 的 DataContext 中搜索此路径。如果 ListView 的 DataContext 未明确设置(如上述情况),则它的 DataContext 与其父级的 DataContext 相同。如果未设置父级的 DataContext - 那么它与父级的父级的 DataContext 相同,依此类推。因此,在这种情况下,ListView 的 DataContext 与 UserControl 的 DataContext 相同,并且是一个包含 Products 集合的 ViewModel 类实例。哒哒! :)
关于c# - 将类对象绑定(bind)到 wpf 中的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10379565/