在IValueConverter上进行数据绑定

Inf*_*ris 7 data-binding wpf dependencyobject ivalueconverter

有人知道是否可以在基于IValueConverter的类上进行数据绑定?

我有以下转换器:

[ValueConversion(typeof(int), typeof(Article))]
public class LookupArticleConverter : FrameworkElement, IValueConverter {
    public static readonly DependencyProperty ArticlesProperty = DependencyProperty.Register("Articles", typeof(IEnumerable<Article>), typeof(LookupArticleConverter)); 

    public IEnumerable<Article> Articles
    {
        get { return (IEnumerable<Article>)GetValue(ArticlesProperty); }
        set { SetValue(ArticlesProperty, value); }
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        ...
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

它的目的是通过Id查找列表中的文章,并返回该文章.

但是,我想通过将一个集合数据绑定到它来填充Articles属性,如下所示:

<local:LookupArticleConverter Articles="{Binding Articles}" x:Key="LookupArticle"/>
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用.永远不会调用setter方法.source属性包含一个实际的非空集合,所以这不是问题.

两者都没有关于输出日志中的绑定的错误消息.

有线索吗?

sur*_*fen 10

所以,问题是资源不是可视化树的一部分.为了完成这项工作,你必须:

1.让ValueConverter继承Freezable

 public class CustomConverter : Freezable, IValueConverter
 {

    public static readonly DependencyProperty LookupItemsProperty =
        DependencyProperty.Register("LookupItems", typeof(IEnumerable<LookupItem>), typeof(CustomConverter), new PropertyMetadata(default(IEnumerable<LookupItem>)));

    public IEnumerable<LookupItem> LookupItems
    {
        get { return (IEnumerable<LookupItem>)GetValue(LookupItemsProperty); }
        set { SetValue(LookupItemsProperty, value); }
    }

    #region Overrides of Freezable

    /// <summary>
    /// When implemented in a derived class, creates a new instance of the <see cref="T:System.Windows.Freezable"/> derived class.
    /// </summary>
    /// <returns>
    /// The new instance.
    /// </returns>
    protected override Freezable CreateInstanceCore()
    {
        return new CustomConverter();
    }

    #endregion Overrides of Freezable

    // ... Usual IValueConverter stuff ...

}
Run Code Online (Sandbox Code Playgroud)

2.使用Binding ElementName绑定到可视树

<UserControl (...) x:Name=myUserControl> 
<UserControl.Resources>
<CustomConverter x:Key="customConverter"
                    LookupItems="{Binding ElementName=myUserControl, Path=DataContext.LookupItems}"/>
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)


Ken*_*art 3

WPF 本质上并不真正支持这一点。然而,有一些技术可以让您做到这一点,包括 Josh Smith 的虚拟分支方法