【问题标题】:How to bind ListBox to a member of a view model in xaml?如何将 ListBox 绑定到 xaml 中的视图模型的成员?
【发布时间】:2013-08-26 12:22:08
【问题描述】:

我只是从 wpf/vmmv 开始。我见过将集合绑定到列表框的示例。示例:在 xaml 中,在代码隐藏(例如页面)中“DataContext = collection..”。

我的视图模型具有更多的属性,而不仅仅是需要绑定到视图的单个集合。因此,我想将视图模型设置为视图的 DataContext,然后在 xaml 中将视图模型的集合绑定到 ListBox。假设我的视图模型设置为 DataContext 并且它有一个名为“Customers”的属性,那么将属性绑定到 xaml 中的 ListBox 的正确方法是什么? 我试过了,还是不行。

谢谢。

【问题讨论】:

    标签: wpf mvvm wpf-controls


    【解决方案1】:

    你的意思是'如何将集合绑定到'ListBox'?你可以这样做:

    <ListBox ItemsSource="{Binding Customers}" />
    

    或者这个:

    <ListBox ItemsSource="{Binding Path=Customers}" />
    

    如果你想绑定Customer 类的每个实例的内部值,你可以这样做:

    <ListBox ItemsSource="{Binding Customers}" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text="{Binding Age}" />
                <TextBlock Text="{Binding EyeColour}" />
            </DataTemplate>
        </ListBox.ItemTemplate>        
    </ListBox>
    

    【讨论】:

    • 你打败了我,不错 :)
    • 在问这个问题之前,我已经尝试过 ItemsSource="{Binding Customers}" 但没有成功。您的回答让我回顾了代码并注意到 Customers 属性不是公开的。奇怪的是我没有得到任何反馈,但我想这是意料之中的。您使用 DataTemplate 的示例将非常有帮助。
    【解决方案2】:

    我猜你想显示属性“Customers”,你要做的就是定义ListBox的ItemTemplate,在ItemTemplate里面定义DataTemplate,然后把Customers绑定到一个控件,如下:

    <ListBox ItemsSource="{Binding}" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Customers}"/>
                ......something else you want display
            </DataTemplate>
        </ListBox.ItemTemplate>
    
    </ListBox>
    

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      相关资源
      最近更新 更多