【问题标题】:Binding to margin as a setter value of a style作为样式的设置器值绑定到边距
【发布时间】:2018-09-03 14:57:34
【问题描述】:

我正在尝试将图表轴标签的边距绑定到属性。

我认为这将是下面代码的一个简单案例(它可以在没有绑定的情况下工作)。

XAML

           <DVC:LinearAxis Orientation="X" Interval="0.5" ShowGridLines="True">
                <DVC:LinearAxis.AxisLabelStyle>
                    <Style TargetType="{x:Type DVC:AxisLabel}">
                        <Setter Property="Margin" Value="{Binding LabelMargin}" />
                    </Style>
                </DVC:LinearAxis.AxisLabelStyle>
            </DVC:LinearAxis>

查看模型

private Thickness _labelMargin;

public Thickness LabelMargin
        {
            get { return _labelMargin; }
            set { SetPropertyAndNotify(ref _labelMargin, value); }
        }

这对利润没有影响,关于我做错了什么有什么想法吗?

编辑:我在输出窗口中收到以下错误

System.Windows.Data 错误:40:BindingExpression 路径错误:在“对象”“Double”(HashCode=1072693248)上找不到“LabelMargin”属性。绑定表达式:路径=标签边距; DataItem='双' (HashCode=1072693248);目标元素是'NumericAxisLabel'(名称='');目标属性是“边距”(类型“厚度”)

【问题讨论】:

  • 看起来 LinearAxis 的 DataContext 错误(即不是您的 ViewModel)
  • 我刚刚尝试在 LinearAxis 上显式设置 DataContext,没有任何变化。我有很多其他属性绑定到这个视图中的视图模型,这些都很好。这是样式设置器中唯一的一个。

标签: c# wpf mvvm data-binding


【解决方案1】:

这样的事情怎么样:

<DVC:LinearAxis Orientation="X" Interval="0.5" ShowGridLines="True">
   <DVC:LinearAxis.AxisLabelStyle>
      <Style TargetType="{x:Type DVC:AxisLabel}">
         <Setter Property="Margin" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DVC:LinearAxis}}, Path=DataContext.LabelMargin}" />
      </Style>
   </DVC:LinearAxis.AxisLabelStyle>
</DVC:LinearAxis>

【讨论】:

  • 这很奏效。我不明白为什么:-/
  • @mister_b 显然 AxisLabelStyle 不会继承(或以某种方式覆盖)当前的 DataContext。因此,您必须使用其祖先元素的 DataContext。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
  • 2021-10-24
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
相关资源
最近更新 更多