【问题标题】:WPF Data Binding ViewModel property to ListBox inside a User Control in code behindWPF Data Binding ViewModel 属性到后面代码中用户控件内的 ListBox
【发布时间】:2016-05-12 06:32:34
【问题描述】:

我正在尝试在后面的代码中动态绑定一个 VM 属性(一个可观察的集合)到 listBox 中的图像,该图像位于我在窗口上显示的用户控件内, 但它不起作用。

这是用户控件的 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>

这是外窗口 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"/>

这就是我在窗口的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);

感谢您的帮助。 谢谢

【问题讨论】:

    标签: c# wpf xaml data-binding


    【解决方案1】:

    您的 XAML 上的一切看起来都很奇怪...但如果您执行以下操作: you.MazeListBox.SetBinding(ListBox.DataContextProperty, youBinding) 或者 you.SetBinding(UserControl.DataContextProperty, youBinding) 甚至you.MazeListBox.SetBinding(ListBox.ItemsSourceProperty, youBinding)(您必须删除绑定到您的xaml)。

    你应该有预期的结果。

    但是,为什么要在这一点上进行绑定而不仅仅是设置 DataContext? you.DataContext = VM_MazeDisplay 之类的东西(假设 VM 的实例是以这种方式调用的)。

    另外,你为什么把你的ListBox 放到WrapPanel 中?

    【讨论】:

    • 完美运行,谢谢!所有这些都是为了进一步的计划,但与此同时,这就是我得到的
    • 好的!很高兴有帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多