【问题标题】:How to bind the Binding.Converter property?如何绑定 Binding.Converter 属性?
【发布时间】:2015-02-26 12:28:00
【问题描述】:

我想绑定到Converter 属性,而不是使用{StaticResource ResourceKey} 作为它的值。

实际上,我有一个 ListView 与自定义 UserControl 作为 ItemTemplate。项目使用ItemConverter : IValueConverter 进行绑定。当我在 UserControl.Resources 中声明我的转换器时,会为每个列表项创建一个 ItemConverter 的实例,这完全没有必要。我想创建一个转换器实例并将其传递给每个项目,因此我可以在我的用户控件中执行以下操作:

<!-- not working -->
<TextBlock 
    Text="{Binding Converter={Binding something}}"
    Foreground="Black"
    FontSize="40"
    />

是否有可能在 Windows 8.1 和 Windows Phone 8.1 的通用商店应用程序中以某种方式做到这一点?有什么想法可以完全避免这样做吗?

我发现了一些与通用应用程序不兼容的过时项目:

通用应用程序有类似的东西吗?

【问题讨论】:

    标签: .net xaml data-binding windows-store-apps windows-phone-8.1


    【解决方案1】:

    我想创建一个转换器实例

    我在我的博客 (Xaml: Call Binding Converter Without Defining StaticResource in Xaml Thanks to Markup Derived Base Class in C#) 上写了一篇关于这种操作的方法的文章。

    让我解释一下我自己的文章。


    一旦使用基类的单例定义了转换器,就不必在页面的资源中创建转换器。

    public class BooleanToVisibilityReverseConverter : 
                             CoverterBase<BooleanToVisibilityReverseConverter>, 
                             System.Windows.Data.IValueConverter
    

    这是一个在 Xaml 中访问的示例(没有在页面资源中创建静态),只是对转换器的简单命名空间访问:

    <DataGrid Grid.Row="1"
              Visibility="{Binding IsEditing, 
                           Converter={ converters:BooleanToVisibilityReverseConverter } 
                          }">
    

    随后直接在命名空间中进行访问,并且为每个页面只创建一个。

    这是基类:

    /// <summary>
    /// This creates a Xaml markup which can allow converters (which inheirit form this class) to be called directly
    /// without specify a static resource in the xaml markup.
    /// </summary>
    public  class CoverterBase<T> : MarkupExtension where T : class, new()
     {
        private static T _converter = null;
    
        public CoverterBase() { }
    
        /// <summary>Create and return the static implementation of the derived converter for usage in Xaml.</summary>
        /// <returns>The static derived converter</returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return _converter ?? (_converter = (T) Activator.CreateInstance(typeof (T), null));
        }
    }
    

    要获得更好的概述,请参阅我的博客文章。

    【讨论】:

    • 感谢您的回答和文章!不幸的是,通用商店应用程序中没有System.Windows.Markup命名空间,也没有MarkupExtension类。我了解您所做的全部想法,但我目前无法使用您的解决方案。将对此主题进行更多研究。
    【解决方案2】:

    目前,该功能不适用于 Windows 8.1 和 Windows Phone 8.1 的 Universal Store Projects。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 2017-05-26
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多