[英]How to capture Listbox selected item
我正在使用MVVM,我的代碼如下
<ListBox Grid.Row="0"
x:Name="myListBox"
ItemsSource="{Binding Path=MyClass}"
ItemTemplate="{StaticResource MyDataTemplate}"
SelectedItem="{Binding Path=SelectedItem}"
HorizontalContentAlignment="Stretch">
</ListBox>
ItemTemplate包含TextBlock
和Label
在我的ViewModel中
public object SelectedItem
{
get
{
return _SelectedItem;
}
set
{
_SelectedItem = value;
//Perform My Command
}
}
只有雙擊后才能選擇該項目。如何使它成為鼠標左鍵? 有什么方法可以將雙擊轉換為單擊?
嘗試這個。 添加MouseUp事件:
<ListBox Grid.Row="0"
x:Name="myListBox"
MouseUp="myListBox_MouseUp"
ItemsSource="{Binding Path=MyClass}"
ItemTemplate="{StaticResource MyDataTemplate}"
SelectedItem="{Binding Path=SelectedItem}"
HorizontalContentAlignment="Stretch">
</ListBox>
並在后面的代碼中:
private void myListBox_MouseUp(object sender, MouseButtonEventArgs e)
{
}
如果要在MVVM中執行此操作,則需要使用Command作為示例
我不確定這是否是您想要的,但這對我有用:
<ListBox Grid.Row="6"
x:Name="myListBox"
ItemsSource="{Binding Path=MyClassItems}"
SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}"
HorizontalContentAlignment="Stretch">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<Label Content="FooLabel: "/>
<TextBlock Text="{TemplateBinding Content}"/>
</StackPanel>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
您可以將代碼添加到:
private void listBox1_Click(object sender, MouseEventArgs e)
{
//Codes :
}
或者,當您在ListBox中雙擊時,可以引發此事件:
private void listBox1_DoubleClick(object sender, EventArgs e)
{
listBox1.Click+=listBox1_Click;
}
更新:如果要在單擊項目后做某事,實際上是在單擊時更改了選定項目的索引,那么您將引發一個名為listBox1_SelectedIndexChanged
的事件。 因此,您要做的就是在此事件中添加代碼。
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//Your Codes .....
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.