在IValueConverter上进行数据绑定

7

请问是否有可能在基于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) {
        ...
    }
}

它的目的是通过ID在列表中查找文章并返回该文章。

然而,我想通过数据绑定将集合填充到Articles属性中,像这样:

<local:LookupArticleConverter Articles="{Binding Articles}" x:Key="LookupArticle"/>

但这似乎不起作用。设置方法从未被调用。源属性包含一个实际的非空集合,所以这不是问题。
输出日志中没有关于绑定的错误信息。
有任何线索吗?

http://www.codeproject.com/Articles/71348/Binding-on-a-Property-which-is-not-a-DependencyPro - Mohsen
3个回答

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 ...

}

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

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

我已经创建了它,但是LookupItems没有绑定并且CreateInstanceCore()没有执行,尽管我设置了断点。 - Mohsen

3

WPF实际上并不支持这个内在功能。然而,有一些技术可以让您做到这一点,包括Josh Smith的虚拟分支方法


0
我已经在绑定语句中添加了RelativeSource方法。这解决了我的问题,即当我将IValueConverter定义在Control.Resources.ResourceDictionary树下,并尝试从Control.DataContext获取DataContext时的问题。
<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Resources/Text.xaml"/>
            <ResourceDictionary Source="/Resources/Layout.xaml"/>
            <ResourceDictionary Source="/Resources/Colours.xaml"/>
            <ResourceDictionary Source="/Resources/Icons.xaml"/>
        </ResourceDictionary.MergedDictionaries>

        <conv:OrientationConverter x:Key="OerientationConverter" IsOrientationRuleEnabled="{Binding Path=DataContext.IsSiteLayoutPhysical, RelativeSource={RelativeSource AncestorType={x:Type UserControl}, Mode=FindAncestor}}"/>
....
<ListView x:Name="operationsListView" ItemsSource="{Binding .}" DataContext="{Binding GroupedPlantItems}" ItemsPanel="{DynamicResource ItemsPanelTemplate1}" Panel.ZIndex="-10">
            <ListView.GroupStyle>
                <GroupStyle>
                    <GroupStyle.Panel >
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="{Binding Name, Converter={StaticResource OerientationConverter}}"/>
                        </ItemsPanelTemplate>
                    </GroupStyle.Panel>
                    <GroupStyle.ContainerStyle>
                        <Style TargetType="{x:Type GroupItem}">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type GroupItem}">
                                        <GroupBox Header="{Binding Name}">
                                            <ItemsPresenter/>
                                        </GroupBox>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </GroupStyle.ContainerStyle>
                </GroupStyle>
            </ListView.GroupStyle>
        </ListView>

我在这里玩了个小花招,通过一个IValueConverter中定义的规则来改变StackPanel定位其内容的方式。我使用转换器上的绑定来从我的ViewModel中禁用或启用规则。我也可以通过这种方法设置规则,或者传递一个lambda表达式进行验证。请原谅我的打字错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接