[英]Get the Selected ListBox item MVVM
我已經完成了以下工作:
public string X
{
get { return _X; }
set
{
_X= value;
NotifyOfPropertyChange("X");
}
}
XAML:
<ListBox SelectedItem="{Binding X}" Grid.Row="0" Grid.Column="2" SelectedIndex="0" Margin="0 10 0 0">
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource MaterialDesignToolToggleListBoxItem}">
<Setter Property="Padding" Value="8 12 8 12" />
</Style>
</ListBox.Resources>
<ListBoxItem>
<TextBlock Text="TEXT1"/>
</ListBoxItem>
<ListBoxItem>
<TextBlock Text="TEXT2"/>
</ListBoxItem>
<ListBoxItem>
<TextBlock Text="TEXT3"/>
</ListBoxItem>
</ListBox>
我得到的不僅僅是以下內容:
System.Windows.Controls.ListBoxItem:SELECTED_ITEM_HERE
您必須轉換文本塊並設置_x
文本
private string _X;
public object X
{
get { return _X; }
set
{
var a = ((ListBoxItem)value).Content as TextBlock;
_X = a.Text;
NotifyOfPropertyChange("X");
}
}
可以直接在xaml中指定listview項目,而可以將這些值綁定到itemssource。
我已經嘗試過以下代碼片段
public Class1()
{
TextList = new ObservableCollection<string> { "TEXT1", "TEXT2" };
}
private string _X;
public string X
{
get { return _X; }
set
{
_X = value;
if (PropertyChanged != null)
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("X"));
}
}
public ObservableCollection<string> TextList { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
在xaml中
<ListBox SelectedItem="{Binding X}" ItemsSource="{Binding TextList}"/>
這樣我只得到“ TEXT2” /“ TEXT1”,而不是控件類型。
而不是添加的ListBoxItems
到ListBox
,你應該添加strings
給它:
<ListBox SelectedItem="{Binding X}" Grid.Row="0" Grid.Column="2" SelectedIndex="0" Margin="0 10 0 0"
xmlns:s="clr-namespace:System;assembly=mscorlib">
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource MaterialDesignToolToggleListBoxItem}">
<Setter Property="Padding" Value="8 12 8 12" />
</Style>
</ListBox.Resources>
<s:String>TEXT1</s:String>
<s:String>TEXT2</s:String>
<s:String>TEXT3</s:String>
</ListBox>
另一個選擇是將源屬性的類型更改為ListBoxItem
但這不是您想要的。 綁定到SelectedItem
的項目類型和屬性的source屬性必須匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.