【问题标题】:How to bind resources properties in a DataTemplate如何在 DataTemplate 中绑定资源属性
【发布时间】:2015-12-16 10:06:51
【问题描述】:

大家好,我有以下数据模板:

    <DataTemplate DataType="Integer">
        <StackPanel>
            <xctk:IntegerUpDown Minimum="{Binding XPath=Min}"
                                Maximum="{Binding XPath=Max}"
                                Increment="{Binding XPath=Inc}"
                                ClipValueToMinMax="True" 
                                AllowSpin="True">
                <xctk:IntegerUpDown.Resources>
                    <converters:Parameter x:Key="IntegerParameter"
                        CurrentDevice="{Binding ElementName=Dock, Path=DataContext.CurrentDevice}"
                        ParameterName="{Binding RelativeSource={RelativeSource TemplatedParent}, XPath=@RegisterName}"
                        ParameterType="Integer">
                    </converters:Parameter>
                </xctk:IntegerUpDown.Resources>
                <xctk:IntegerUpDown.Value>
                    <Binding XPath="@Name" 
                             Converter="{StaticResource IntegerDataConverter}" 
                             ConverterParameter="{StaticResource IntegerParameter}" 
                             Mode="TwoWay"/>
                </xctk:IntegerUpDown.Value>
            </xctk:IntegerUpDown>
        </StackPanel>
    </DataTemplate>

此数据模板的目的是调用转换器来设置 IntegerUpDown 控件的值,从外部设备读取它。

如何联系设备的详细信息存储在转换器:参数类(派生自依赖对象)中。两种方式意味着应该使用相同的机制与 ConvertBack 一起将值写入设备。

MultiBinding 不是一个选项,因为 ConvertBack 方法不能用于从单个整数值“创建”所有参数。

此模板几乎按预期工作:我为应用数据模板的每个项目获取了一个 Parameter 类的实例。

不幸的是,CurrentDevice(应该绑定到名为“Dock”的窗口的 DataContext 属性 CurrentDevice)和 ParameterName(应该绑定到应用 DataTemplate 的 Xml 节点的 Xml 属性)的值始终为空。

我确定问题出在我尝试绑定 Parameter 属性的方式上,但我无法找出正确的语法。关于如何获得结果的任何想法(我不敢相信这不能完成......)。

感谢您提供的任何帮助

【问题讨论】:

  • 绑定时有 XPath 属性吗?你确定这是正确的,你不是要使用“路径”吗?我从来没有听说过这个属性,也没有在智能感知中注意到它
  • 是的。事实上,我的转换器将 Name 属性的值作为值形式参数。当您的 itemsource 是 XmlDocument 时,您使用 XPath 而不是 Path。
  • 我猜想知道很有趣。从来没有我的 itemssource 是 XmlDocument 的情况。但是我可以给你一个建议:Textblock Text="{Binding Path=.} 帮助我找到了 WPF 中的许多绑定问题。

标签: c# wpf xaml


【解决方案1】:

您可能猜到我的想法是尝试为“您无法绑定 ConverterParameter”问题找到解决方法。

在互联网上进一步研究后,我发现了这篇文章:

Bindable Converter Parameter

来自这个 ntg123 的家伙。它实际上解决了我的问题,允许使用与标准语法几乎相同的语法以某种方式将 ConverterParameter 绑定到多个源。

它基于自定义的 MarkupExtension,在无法进行多重绑定的情况下工作得非常好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-14
    • 2011-07-21
    • 2023-03-04
    • 1970-01-01
    • 2022-11-14
    • 2015-09-09
    • 2013-01-01
    • 2018-09-30
    相关资源
    最近更新 更多