[英]WPF Data Binding ViewModel property to ListBox inside a User Control in code behind
I'm trying to bind dynamically, in code behind, a VM property (an obseravble collection) to image in listBox that sits inside a usercontrol I show on my window, but it's not working. 我试图在背后的代码中动态绑定VM属性(可观察的集合)到listBox中的图像,该列表位于我在窗口上显示的用户控件内,但不起作用。
This is the XAML of the user control: 这是用户控件的XAML:
<WrapPanel x:Name="panel" HorizontalAlignment="Center" Focusable="False" FocusManager.IsFocusScope="False">
<ListBox x:Name="MazeListBox" ItemsSource="{Binding}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid x:Name="MazeUniformGrid" Columns="{Binding VM_MazeCols}" Rows="{Binding VM_MazeRows}"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Image x:Name="Img" Margin="-6" Source="{Binding}" Focusable="False"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</WrapPanel>
This are the usercontrols in XAML of the Outer Window: 这是外部窗口的XAML中的用户控件:
<Controls:MazeBoard1 x:Name="you" Margin="0,0,650,0" Grid.Column="0" Height="Auto" Width="Auto" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Controls:MazeBoard1 x:Name="other" Margin="650,0,0,0" Grid.Column="0" Height="Auto" Width="Auto" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center"/>
This is how I bind dynamically in the cs of the window: 这是我在窗口的CS中动态绑定的方式:
Binding youBinding = new Binding
{
Path = new PropertyPath("VM_MazeDisplay"),
};
Binding otherBinding = new Binding
{
Path = new PropertyPath("VM_OtherMazeDisplay"),
};
you.MazeListBox.SetBinding( ContentControl.ContentProperty,youBinding);
other.MazeListBox.SetBinding(ContentControl.ContentProperty, otherBinding);
I'll appreciate your help. 多谢您的协助。 Thank you
谢谢
Everything looks weird on your XAML...but if you do the following: you.MazeListBox.SetBinding(ListBox.DataContextProperty, youBinding)
or you.SetBinding(UserControl.DataContextProperty, youBinding)
or even you.MazeListBox.SetBinding(ListBox.ItemsSourceProperty, youBinding)
(you will have to remove the binding into your xaml). 在您的XAML上,一切看起来都很奇怪...但是,如果您执行以下操作:
you.MazeListBox.SetBinding(ListBox.DataContextProperty, youBinding)
或you.SetBinding(UserControl.DataContextProperty, youBinding)
甚至是you.MazeListBox.SetBinding(ListBox.ItemsSourceProperty, youBinding)
(您必须将绑定删除到您的xaml中)。
You should have the expected results. 您应该具有预期的结果。
However, why doing a binding in this point and not just only setting the DataContext? 但是,为什么要在此时进行绑定,而不仅仅是设置DataContext? Something like
you.DataContext = VM_MazeDisplay
(assuming the instance of the VM is called that way). 像您这样的东西
you.DataContext = VM_MazeDisplay
(假设以这种方式调用了VM的实例)。
Also, why do you put your ListBox
into a WrapPanel
? 此外,为什么还要将
ListBox
放入WrapPanel
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.