[英]Clarification on binding Listbox.SelectedItem in MVVM
我在我的一個用戶控件中有一個ListBox
,我希望在ViewModel中使用SelectedItem
。 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>
然后在你的datacontext中設置一個像這樣的字符串Property
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");
}
}
如果您有任何疑問,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.