WPF 按钮列表框:如何使用 XAML 单击时更改所选项目
我有一个模板化的 ListBox
:
<ListBox Grid.Row="0" Grid.Column="1" Background="Transparent" BorderThickness="0" x:Name="mainMenu"
ItemsSource="{Binding Source={x:Static local:MenuConfig.MainMenu}, Mode=OneTime}"
IsSynchronizedWithCurrentItem="True">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="PreviewMouseUp" Handler="SelectCurrentItem"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Button>
<StackPanel>
<Image Source="{Binding Icon}" MaxHeight="32" MaxWidth="32"/>
<TextBlock Text="{Binding Label}"/>
</StackPanel>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
所选项目是通过后面的代码手动更新的:
private void SelectCurrentItem(object sender, MouseButtonEventArgs e)
{
ListBoxItem item = (ListBoxItem) sender;
item.IsSelected = true;
}
有没有办法仅使用 XAML 来执行此操作(单击按钮时更新所选项目)?
I have a templated ListBox
:
<ListBox Grid.Row="0" Grid.Column="1" Background="Transparent" BorderThickness="0" x:Name="mainMenu"
ItemsSource="{Binding Source={x:Static local:MenuConfig.MainMenu}, Mode=OneTime}"
IsSynchronizedWithCurrentItem="True">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="PreviewMouseUp" Handler="SelectCurrentItem"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Button>
<StackPanel>
<Image Source="{Binding Icon}" MaxHeight="32" MaxWidth="32"/>
<TextBlock Text="{Binding Label}"/>
</StackPanel>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The selected item is updated manually with code behind:
private void SelectCurrentItem(object sender, MouseButtonEventArgs e)
{
ListBoxItem item = (ListBoxItem) sender;
item.IsSelected = true;
}
Is there a way to do this (update selected item on button click) with XAML only ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常,如果您想要的效果,您可以将
DataTemplate
设置为看起来像按钮并响应,例如,您可能还需要设置
ItemContainerStyle
来覆盖ItemContainerStyle
的默认样式。代码>所选项目:Typically you style your
DataTemplate
to look and respond like a button if that is the effect you want e.g.You may also want to set the
ItemContainerStyle
to override the default styling for theSelectedItem
:DataTemplate
中定义的按钮将在ListBoxItem
处理该事件之前拦截该单击事件。从DataTemplate
中删除ItemContainerStyle
和Button
。The button defined in your
DataTemplate
will be intercepting the click event before theListBoxItem
can handle it. Remove theItemContainerStyle
and theButton
from yourDataTemplate
.ListBox
会为您跟踪并选择当前项目,您不需要在代码中执行此操作。删除它,您正在做的工作是开箱即用的。
A
ListBox
tracks and selects the current item for you, you dont need to do it in code. remove thisyou are doing work thats done for you out of the box.