【问题标题】:WPF custom toolbarWPF 自定义工具栏
【发布时间】:2013-07-10 23:30:57
【问题描述】:

我是 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>

【问题讨论】:

    标签: wpf toolbar


    【解决方案1】:

    你需要 RelayCommand 类,你可以从 here 获得。

    然后您在 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-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

    【讨论】:

    • Nitesh 感谢您的响应。实际上我需要带有标准按钮的自定义工具栏控件。添加更新删除清除。当我将控件从工具箱拖放到窗口时,工具栏应该加载标准按钮。然后我将命令绑定到按钮
    【解决方案2】:

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

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

    Generic.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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-20
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多