【问题标题】:How do you bind a TextBox to a ListBox's selected member's corresponding property?如何将 TextBox 绑定到 ListBox 的选定成员的相应属性?
【发布时间】:2014-04-07 20:18:11
【问题描述】:

我有一个通知列表:

public List<Notification> Notifications { get; set; }

我的 UI 中的 ListBox 绑定到此列表:

<ListBox ItemsSource="{Binding Notifications}" DisplayMemberPath="ServiceAddress" Name="NotificationsList"/>

在我的 UI 中,我也有这个 TextBox:

<TextBox Name="MatchWindowTextBox"/>

MatchWindow 是 Notification 对象中的一个属性...所以我可以从上面的列表中访问它:Notifications[SomeIndex].MatchWindow。无论如何,当有人更改 ListBox 上的选择时,这实际上会选择不同的通知...那么有什么方法可以将我的 TextBox 绑定到所选通知的 MatchWindow 属性?

【问题讨论】:

    标签: c# wpf xaml binding textbox


    【解决方案1】:

    一种快速的方法是使用ElementName 绑定:

    <TextBox Text="{Binding SelectedItem.MatchWindow, 
                            ElementName=NotificationsList}"/>
    

    但是,更好的方法是在 ViewModel 中创建 Notification 类型的 SelectedItem 属性并绑定到该属性:

    <ListBox ItemsSource="{Binding Notifications}"
             SelectedItem="{Binding SelectedNotification}"/>
    
    <!-- ... -->
    
    <TextBox Text="{Binding SelectedNotification.MatchWindow}"/>
    

    【讨论】:

    • 你介意我扔给你一个小曲线球吗?因为我也在尝试将相同的概念应用于其他事物!
    • 假设我的 Notification 类有一个动作列表,例如 List ActionsList {get; set;},并且我的 Action 上有一个 ActionType 类型的枚举...如果我的 ActionsList 包含某种枚举类型的操作,我如何才能在我的 UI 中制作一个 CheckBox?
    • @Alexandru 将bool 属性放在数据项中,这样您就可以将CheckBox.IsChecked 绑定到该属性,或者使用EnumToBoolConverter,或者使用DataTrigger。您想就此发表一个单独的问题吗?
    • 知道了!谢谢,@HighCore。
    • 我正在慢慢掌握它,但是这个衍生产品呢(在一个新问题中提出)? stackoverflow.com/questions/22205303/…
    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2016-10-04
    • 1970-01-01
    • 2016-03-22
    • 2018-09-03
    相关资源
    最近更新 更多