[英]How to get specific item listbox C# MVVM WPF
Hi i try to get specific item from a listbox.嗨,我尝试从列表框中获取特定项目。 I try to bind but i get crash.
我尝试绑定但我崩溃了。 Using Prism framework how can i bind to get specific item from listbox, what template i need to make.
使用 Prism 框架我如何绑定以从列表框中获取特定项目,我需要制作什么模板。 This is test code:
这是测试代码:
<ListBox SelectedItem="{Binding SelectIndex}" HorizontalAlignment="Left" Height="297" Margin="57,41,0,0" VerticalAlignment="Top" Width="681">
<ListBoxItem>
<TextBlock Text="Test123"/>
</ListBoxItem>
<ListBoxItem>
<TextBlock Text="Test123"/>
</ListBoxItem>
</ListBox>
C# code: C# 代码:
public int SelectIndex
{
get
{
return 1;
}
}
How can i get if i want specific item from this list?如果我想要此列表中的特定项目,我该如何获取? What variable type need to make for binding listbox to select items?
将列表框绑定到 select 项目需要什么变量类型?
It's crashing because you are binding SelectedItem
(of type object
) to your SelectIndex
property ( int
property) in your view model (VM).它崩溃了,因为您将
SelectedItem
(类型为object
)绑定到您的视图 model (VM)中的SelectIndex
属性( int
属性)。 ListBox
like many WPF controls have distinct SelectedIndex
and SelectedItem
properties for binding.像许多 WPF 控件一样,
ListBox
具有用于绑定的不同SelectedIndex
和SelectedItem
属性。
If you want to bind to an int
property in order to get the index you should be binding the ListBox
's SelectedIndex
property instead.如果要绑定到
int
属性以获取索引,则应改为绑定ListBox
的SelectedIndex
属性。
Change:改变:
<ListBox SelectedItem="{Binding SelectIndex}" ...
...to: ...至:
<ListBox SelectedIndex="{Binding SelectIndex}" ...
Your VM remains as:您的虚拟机保持为:
public int SelectIndex { get { return 1; } }
Though to be more useful and allow users to choose different items it should be:虽然更有用并允许用户选择不同的项目,但它应该是:
public int SelectIndex { get; set; } // TODO: add support for INotifyPropertyChanged
Optionally you can add:您可以选择添加:
<ListBox SelectedIndex="{Binding SelectIndex}"
SelectedItem="{Binding SelectedItem}" ...
ViewModel:视图模型:
public int SelectIndex { get; set; } // TODO: add support for INotifyPropertyChanged
// replace object with your type
public object SelectedItem { get; set; } // TODO: add support for INotifyPropertyChanged
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.