c# - 澄清在 MVVM 中绑定(bind) Listbox.SelectedItem

标签 c# wpf mvvm listbox

我的一个用户控件中有一个 ListBox,我想在其中获取要在 ViewModel 中使用的 SelectedItemListBoxTextBlocks 组成。

This question几乎是对我的问题的直接回答,但我不明白 DisneyCharacter(他的集合类型)从哪里来,或者它与 ListBox 有什么关系。

我的类型是 TextBlock 吗?

ListBox 的 XAML 根据要求:

<ListBox Margin="14,7,13,43" Name="commandListBox" Height="470" MinHeight="470" MaxHeight="470" Width="248" >
               <TextBlock Text="Set Output" Height="Auto" Width="Auto" />
               <TextBlock Text="Clear Output" Height="Auto" Width="Auto" />
               <TextBlock Text="Follow Left Tape Edge" Height="Auto" Width="Auto" />
               <TextBlock Text="Follow Right Tape Edge" Height="Auto" Width="Auto" />
               <TextBlock Text="Follow Tape Center" Height="Auto" Width="Auto" /></ListBox>

最佳答案

由于 TextBlock 的输出是一个字符串,您将绑定(bind)到一个字符串属性,您将绑定(bind)到您的 ViewModel 或代码隐藏中的一个字符串。

<ListBox SelectedItem = "{Binding myString}">
     .......
</ListBox>

然后在你的数据上下文中设置一个像这样的字符串属性

public string myString {get; set;}

现在,无论何时单击某个项目,该文本 block 中的文本都将位于 myString 变量中。

如果您使用 MVVM 模型,您的属性将如下所示:

 private string _myString;

    /// <summary>
    /// Sets and gets the myString property.
    /// Changes to that property's value raise the PropertyChanged event. 
    /// </summary>
    public string myString
    {
        get
        {
            return _myString;
        }

        set
        {
            if (_myString == value)
            {
                return;
            }

            RaisePropertyChanging("myString");
            _myString = value;
            RaisePropertyChanged("myString");
        }
    }

如果您有任何问题,请告诉我。

关于c# - 澄清在 MVVM 中绑定(bind) Listbox.SelectedItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19123215/

相关文章:

c# - 模块中的 Prism、Unity 和默认类型注册

c# - 将枚举属性值绑定(bind)到 ListView.Items(WinForms)

c# - 无法将 xml 反序列化为 List<T>

c# - 具有更改哈希码的 WPF 列表框和项目

c# - xaml 按钮模板和按钮上方的按钮

c# - 将 Grid 对象从一个 TabItem 复制到另一个时出现问题

c# - MVVM 灯 : Pass object from view to viewmodel

c# - 如何在 C# 中使用 WebRequest

c# - 按值从 Azure 队列服务中删除消息

c# - WPF 绑定(bind)未正确更新