【发布时间】:2017-07-20 20:58:02
【问题描述】:
我有一个显示 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 变量... 编辑:我仍然对这部分感到困惑......并且想知道这是否是一个问题。我仍在从 XAML 实例创建这个“视图”变量......并将列表分配给 IT......我觉得我需要设置 ViewModel 的 XAML 实例的属性......而不是把它拿到一个变量和设置那个...但看不到如何...或它是如何工作的:/
如果我这样做:
ImageBox1.ItemsSource = view.Box1;
...然后它完美地工作(减去让我发疯的内存泄漏,但这是另一个故事:))...但我似乎无法弄清楚为什么在 XAML 中设置 ItemsSource 不起作用.
【问题讨论】:
-
检查“输出”窗口。通常绑定错误会写在那里。
-
向我展示我的新手编程嘿嘿......这是错误:System.Windows.Data 错误:40:BindingExpression 路径错误:在 'object' ''MainWindow 上找不到 'Box1' 属性'(名称='范围')'。绑定表达式:路径=Box1; DataItem='MainWindow' (Name='Scope');目标元素是'ListBox'(名称='ImageBox1');目标属性是'ItemsSource'(类型'IEnumerable')但是,我认为这是我试图使用DataContext = this;在 MainWindow 中...我认为这是不正确的,因为我在 XAML 中设置了它...尝试删除它...现在我看不到任何即将发生的事情...
-
这很有趣。它正在寻找
MainWindow上的Box1属性,而不是您的ViewModel- 这意味着ListBox的DataContext是MainWindow而不是ViewModel。您在上面粘贴的示例代码不是您的实际代码的样子,或者您正在其他地方设置DataContext属性。 -
是的,请参阅我上一条评论的结尾。我之前正在玩弄它并尝试在 MainWindow 中设置它并忘记将其删除。在没有那个的情况下再次尝试,并且在我删除它之后在输出中没有看到任何有用的东西。谢谢你的想法,现在我知道去那里看看:)
标签: c# wpf mvvm binding dependencies