问题
I have a ListBox
in one of my user controls in which I would like to get the SelectedItem
, to be used in the ViewModel. The ListBox
is composed of TextBlocks
.
This question is pretty much a straight up answer to my question, but I don't understand where DisneyCharacter
(his collection type) comes from, or how it relates to the ListBox
.
Would mine be of type TextBlock
?
XAML for ListBox
as requested:
<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>
回答1:
Since the output from a TextBlock is a string, you would bind to a string property, you would bind to a string in your ViewModel or code behind.
<ListBox SelectedItem = "{Binding myString}">
.......
</ListBox>
Then in whatever your datacontext is set up a string Property like this
public string myString {get; set;}
Now whenever you click on an item, the text from that textblock will be in the myString variable.
if you were using MVVM model your property would look like this:
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");
}
}
Let me know if you have any questions.
来源:https://stackoverflow.com/questions/19123215/clarification-on-binding-listbox-selecteditem-in-mvvm