关于在 MVVM 中绑定 Listbox.SelectedItem 的说明

2024-03-31

我有一个ListBox在我的用户控件之一中,我想获得SelectedItem,在 ViewModel 中使用。这ListBox由...组成TextBlocks.

这个问题 https://stackoverflow.com/questions/1384369/mvvm-binding-to-listbox-selecteditem几乎是对我的问题的直接回答,但我不明白在哪里DisneyCharacter(他的集合类型)来自,或者它与ListBox.

我的会是那种类型吗TextBlock?

XAML 用于ListBox按照要求:

<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 的输出是字符串,因此您将绑定到字符串属性,您将绑定到 ViewModel 或隐藏代码中的字符串。

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

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

public string myString {get; set;}

现在,每当您单击某个项目时,该文本块中的文本都将位于 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");
        }
    }

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关于在 MVVM 中绑定 Listbox.SelectedItem 的说明 的相关文章

随机推荐