我的一个用户控件中有一个 ListBox
,我想在其中获取要在 ViewModel 中使用的 SelectedItem
。 ListBox
由 TextBlocks
组成。
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/