0

我是 WPF 的新手。我想创建带有标准按钮的自定义工具栏,如下所示。当我从工具箱中拖放控件时,所有按钮都应自动添加文本和图像。我还想为每个按钮添加属性 CommandName 以及何时单击我想在视图模型中使用命令名称绑定命令。你能帮帮我吗?

    <ToolBar VerticalAlignment="Top">
        <Button>Add</Button>
        <Separator></Separator>
        <Button>Update</Button>
        <Separator></Separator>
        <Button>Delete</Button>
        <Separator></Separator>
        <Button>Clear</Button>
        <Separator></Separator>
        <Button>Logout</Button>
        <Separator></Separator>
        <Button>Excel</Button>

    </ToolBar>
4

2 回答 2

0

您将需要可以从这里获得的 RelayCommand 类。

然后您在 ViewModel 中创建一个 RelayCommand 并将命令与您的按钮绑定,如下所示

<Button Command="{Binding YourCommandName}">

所以基本上你需要一个自定义控件。将这些按钮放在自定义控件的控件模板中。公开这些按钮的点击事件。假设添加按钮的单击事件的名称是 ClickAdd。然后将如下命令绑定到 XAML 中的添加按钮

<local:YourCustomControl>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="ClickAdd">
            <i:InvokeCommandAction Command="{Binding YourCommandName}">  </i:InvokeCommandAction>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</local:YourCustomControl>

xmlns:i="clr-命名空间:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

于 2013-07-11T02:51:39.927 回答
0

非常感谢你。问题是我没有设置 DefaultStyleKey。所以当我从工具箱中拖放控件时,我在 controltemplate 中添加的按钮没有出现在 window.basicly 解决方案是

 public class StToolBar:ToolBar
    {
        public StToolBar()
        {
            this.DefaultStyleKey = typeof(StToolBar);
        }
    }

通用的.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:UserControl">
    <Style TargetType="{x:Type local:StToolBar}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:StToolBar}">
                        <ToolBar>
                            <Button>Add</Button>
                            <Button>Update</Button>
                        </ToolBar>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>


</ResourceDictionary>
于 2013-07-11T07:55:52.873 回答