【问题标题】:Styling button in MVVMMVVM 中的样式按钮
【发布时间】:2012-05-12 07:01:16
【问题描述】:

我正在使用 MVVM 模式编写一个小型 WPF 应用程序。

我为我的主窗口中的按钮设置了一些样式资源,我希望它们应用于视图中的按钮。问题是某些按钮具有带触发器的样式。所以我想从通用的继承这种风格

这是我的主窗口代码:

 <Window.Resources>
    <DataTemplate DataType="{x:Type vm:HomeViewModel}">
        <views:HomeView/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:DetailReportViewModel}">
        <views:DetailReportView/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:TransferViewModel}">
        <views:TransferView/>
    </DataTemplate>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Margin" Value="5"/>
        <Setter Property="MinWidth" Value="30"/>
        <Setter Property="Foreground" Value="Red"/>

    </Style>
    <Style TargetType="{x:Type ComboBox}">
        <Setter Property="Margin" Value="5"/>
    </Style>
   </Window.Resources>

这是我的视图/用户控件中的 XAML 按钮

<Button Content="Delete" Command="{Binding DeleteReportCommand}">
            <Button.Style>
                <Style TargetType="{x:Type Button}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Mode}">
                            <DataTrigger.Value>
                                <vm:Mode>Add</vm:Mode>
                            </DataTrigger.Value>
                            <Setter Property="Visibility" Value="Collapsed"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Mode}">
                            <DataTrigger.Value>
                                <vm:Mode>Edit</vm:Mode>
                            </DataTrigger.Value>
                            <Setter Property="Visibility" Value="Visible"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>

我尝试使用 BasedOn="{StaticResource {x:Type Button} 继承,但它似乎不起作用(见 img)

我尝试使用键名,但静态资源找不到键名,因为它不在同一个视图中。并且 BasedOn 不接受动态资源。 我有什么遗漏吗?

谢谢

【问题讨论】:

  • 我在面板资源中定义了按钮的 stile 并且有同样的问题,但我不想将样式移动到 app.xaml 很高兴知道上述方法失败的原因。跨度>

标签: mvvm styles basedon


【解决方案1】:

您可以将所有自定义样式放在单独的资源字典文件中,也可以将其添加到 usercontrol.resources 中。

请参考:http://www.codeproject.com/Articles/35346/Using-a-Resource-Dictionary-in-WPF

或者您可以将所有这些都放在 app.xaml (Application.Resources) 中。

参考这个:http://msdn.microsoft.com/en-us/library/system.windows.resourcedictionary.aspx

【讨论】:

  • 谢谢。我将所有内容都放入了 app.xaml。我不知道我为什么不早点尝试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多