我的一个用户控件中有一个ListBox
,我想在其中获取SelectedItem
,以便在ViewModel中使用。ListBox
由TextBlocks
组成。
这个问题几乎是对我问题的直接回答,但我不明白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 的输出是一个字符串,因此您将绑定到字符串属性,您将绑定到 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");
}
}
如果您有任何问题,请告诉我。