【问题标题】:Bind to a MainPage Property out of DataTemplate绑定到 DataTemplate 之外的 MainPage 属性
【发布时间】:2014-01-28 13:27:54
【问题描述】:

我正在尝试将 MainPage (CodeBehind) 中定义的对象绑定到 ListView DataTemplate 中的 ConverterParameter:

<ListView ...>
  <ListView.ItemTemplate>
    <DataTemplate>
      <TextBlock Text=".. SomeBindingExpression"
   FontWeight="{Binding Converter={StaticResource ChangeDateToFontWeightConverter},ConverterParameter={Binding Source=MainPage,Path=Cache}}"/>
      </TextBlock>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

目标是将 MainPage 中定义的“缓存”对象传递给转换器。上述代码正确调用转换器,但传递的对象参数为空。有没有办法在这个 XAML 代码中引用 Cache 对象?

【问题讨论】:

    标签: c# wpf xaml windows-runtime


    【解决方案1】:

    ConverterParameter 接受一个字符串,根本不能进行数据绑定。 您可以向转换器类添加自定义属性,并在 MainPage 的代码隐藏中传递您的“缓存”对象。

    ((ChangeDateToFontWeightConverter)this.Resources["ChangeDateToFontWeightConverter"]).MyCustomProperty = myCacheObject;
    

    一般来说,我建议采用MVVM 方法并使用缓存对象中的所需数据扩展您的数据绑定类(如果可能)。这样你就完全不需要转换器了。

    【讨论】:

    • 这种方法能胜任!但是您在扩展数据绑定类方面是正确的。现在我在 MainPage 中管理缓存处理,并在扩展的数据绑定类中设置所需的数据。我没有摆脱转换器,但现在它是一个“BooleanToFontWeightConverter”——很简单。感谢您删除我的“CodeBlindness”。
    猜你喜欢
    • 2012-04-11
    • 2018-09-30
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 2019-10-19
    • 2013-01-01
    相关资源
    最近更新 更多