WPF绑定/依赖属性(List)

时间:2017-07-20 20:58:02

标签: c# wpf mvvm binding dependencies

我有一个显示2个图像列表框的应用程序。它们是相同的图像,但顺序不同。比较每个订单中的位置是相关的,因此我为每个列表框使用单独的列表。

List有几个依赖属性,因此我可以显示几个属性以及图像本身。

简单地说,我填充了2个List实例。 ImageCrawler类中的属性都是依赖属性。

我几乎没有掌握MVVM,所以请原谅这个丑陋的东西 - 我使用另一个类 - ViewModel,它拥有2个列表,也是dep。属性如下:

public class ViewModel : DependencyObject
{

    public List<ImageCrawler> Box1
    {
        get { return (List<ImageCrawler>)GetValue(ImageProperty); }
        set { SetValue(ImageProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ImageProperty =
        DependencyProperty.Register("Box1", typeof(List<ImageCrawler>), typeof(ViewModel));





    public List<ImageCrawler> Box2
    {
        get { return (List<ImageCrawler>)GetValue(Image2Property); }
        set { SetValue(Image2Property, value); }
    }

    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty Image2Property =
        DependencyProperty.Register("Box2", typeof(List<ImageCrawler>), typeof(ViewModel));

}

所以这两个列表存储在这个类中。

问题是有约束力的。这是我在XAML中的一个列表框(在另一个中镜像)的代码:

<ListBox ItemsSource="{Binding Box1}"
         DataContext="{StaticResource ViewModel}"
         x:Name="ImageBox1"
         HorizontalAlignment="Left"
         Margin="10,109,0,10"
         Width="173"
         SelectionChanged="ImageBox1_SelectionChanged">
    <ListBox.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}">
            <SolidColorBrush.Color>#FF3399FF</SolidColorBrush.Color>
        </SolidColorBrush>
    </ListBox.Resources>
</ListBox>

这里的StaticResource可以在App.xaml中找到:

<Application.Resources>
    <local:ViewModel x:Key="ViewModel" />
</Application.Resources>

所以这些列表的填充方式...... 首先,我在MainWindow中有这个字段:

public static ViewModel view = Application.Current.FindResource("ViewModel") as ViewModel;

...据我所知,它指的是App.xaml中的实例。

单击一个按钮,逻辑将获取ImageCrawler对象列表,将它们放入列表中,然后将列表分配给上面定义的视图变量...但绑定不起作用:(。 ..其他所有内容......所以我这样做是为了将我刚刚获得的列表分配给视图:

view.Box1 = Box1;

...其中Box1是List变量...... 编辑:我仍然对这一部分感到困惑......并且想知道它是否是一个问题。我还在制作这个&#34;观看&#34;变量从XAML实例...并将列表分配给IT ...我觉得我需要设置ViewModel的XAML实例的属性...不要将它变为变量并设置为...但不要#39 ;看看如何...或如何工作:/

如果我这样做:

ImageBox1.ItemsSource = view.Box1;

...然后它完美地工作(减去内存泄漏,这让我疯了,但那是另一个故事:))......但我似乎无法弄清楚为什么在XAML中设置ItemsSource不会起作用。

1 个答案:

答案 0 :(得分:0)

您根本不应该设置ListBox的DataContext。而不是将ViewModel创建为资源,而是将其直接分配给Window的DataContext,并让子元素继承DataContent:

<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>
...

<!-- ListBox DataContext is inherited from Window -->
<ListBox ItemsSource="{Binding Box1}" ...>

在后面的代码中,您可以像这样访问ViewModel实例:

private void someMethodInMainWindow()
{
    var viewModel = (ViewModel)DataContext;
    viewModel.Box1 = ...
}