gpt4 book ai didi

c# - 如何将 "click"处理程序添加到作为控件模板一部分的按钮?

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:06 25 4
gpt4 key购买 nike


我有一个控制模板:(1)

<Style x:Key="customItemStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<ToggleButton>
<Grid Width="260" Height="58">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="58"/>
<ColumnDefinition Width="202"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="{StaticResource image_resourse}"/>
<Button Grid.Column="1"> Button text </Button>
</Grid>
</ToggleButton>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

它用于自定义 ListBoxItems,如下所示:(2)

<ListBox>
...
<ListBoxItem Style="{StaticResource customItemStyle}">
...
</ListBox

我想在将样式应用于 ListBoxItem 时设置位于该模板内的 Button 的 Click 处理程序。(1) - 来自样式文件的代码(2) - 来自一些组件定义文件的代码

我该怎么做?

最佳答案

这样做的方法是在模板上定义一个ICommand。这样,您就可以轻松地将处理程序绑定(bind)到您需要的任何代码。

从子类化 ListBoxItem 开始,并包含“ICommand”依赖属性:

public class CommandListBoxItem : ListBoxItem 
{
public static readonly DependencyProperty ButtonCommandProperty =
DependencyProperty.Register("ButtonCommand", typeof(ICommand), typeof(CommandListBoxItem), null);
public bool ButtonCommand
{
get { return (ICommand)GetValue(ButtonCommandProperty); }
set { SetValue(ButtonCommandProperty, value); }
}

public CommandListBoxItem()
{
DefaultStyleKey = typeof(CommandListBoxItem);
}
}

现在修改控件模板以将命令链接到按钮单击:

<Style x:Key="customItemStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type custom:CommandListBoxItem}">
<ToggleButton>
<Grid Width="260" Height="58">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="58"/>
<ColumnDefinition Width="202"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="{StaticResource image_resourse}"/>
<Button Grid.Column="1" Command="{TemplateBinding ButtonCommand}"> Button text </Button>
</Grid>
</ToggleButton>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

最后,将命令属性绑定(bind)到 View 模型(或代码隐藏)中的命令:

<ListBox>
...
<custom:CommandListBoxItem Style="{StaticResource customItemStyle}"
ButtonCommand="{Binding CommandFromViewModel}" />
...
</ListBox>

关于c# - 如何将 "click"处理程序添加到作为控件模板一部分的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22048773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com