【问题标题】:Binding styles from ResourceDictionary to usercontrols将样式从 ResourceDictionary 绑定到用户控件
【发布时间】:2017-04-15 23:29:52
【问题描述】:

我是 wpf 的新手,所以我正在寻找解决方案并解释为什么我尝试的解决方案不起作用。

这是我的情况。 我有几个用户控件。在他们每个人中,我都应用以下样式:

<UserControl.Resources>
    <Style TargetType="TextBox" BasedOn="{StaticResource Centratura}">
        <Setter Property="IsEnabled" Value="{Binding Property1.IsAbilitato}" />
    </Style>
</UserControl.Resources>

基于资源字典中定义的样式。 而且效果很好。 但请注意,对于每个 UserControl,前面的代码都是相同的,除了绑定属性,即 Property1.IsAbilitato、Property2.IsAbilitato、Property3.IsAbilitato...

但这是我不喜欢的代码重复。我想知道如何将样式放入资源字典并稍后在每个用户控件中应用正确的绑定。

我尝试像here 所建议的那样使用 Tag 属性,这样:

在我的用户控件中:

<UserControl x:Class="whatever"
    ...
    Tag="{Binding Property1.IsAbilitato}"
    ...>

在资源字典中:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="TextBox">
        <Setter Property="IsEnabled" Value="{Binding Path=Tag, RelativeSource={RelativeSource Self}}" />
        <Setter Property="HorizontalContentAlignment" Value="Center" />
    </Style>
</ResourceDictionary>

但它不起作用。建议?其他解决方案? (如果相关,我正在使用 MVVM)。 提前致谢。

【问题讨论】:

  • 您是否将该资源文件应用到您的 app.xaml 中?
  • 是的,我做到了。它适用于其他东西。

标签: wpf xaml binding resourcedictionary


【解决方案1】:

您必须将标签添加到 TextBox 本身:

<TextBox Tag="{Binding Property1.IsAbilitato}"/>

如果您希望以下工作:

 <Setter Property="IsEnabled" Value="{Binding Path=Tag, RelativeSource={RelativeSource Self}}" />

但如果你想将它添加到 UserControl 并希望应用所有 TextBox,那么你必须将其更改为:

<Setter Property="IsEnabled" Value="{Binding Path=Tag, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2017-06-05
    • 2012-02-08
    • 2011-01-05
    • 1970-01-01
    • 2013-07-07
    相关资源
    最近更新 更多