如何仅在WPF';s绑定

本文关键字:绑定 何仅 WPF | 更新日期: 2023-09-27 18:20:42

我有一个自定义绑定,如下所示:

public class MyBinding : Binding
{
    public class ValueConverter : IValueConverter
    {
        public ValueConverter(string A)
        {
            this.A = A;
        }
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if ((bool)value == true)
            {
                return A;
            }
            else
            {
                return "another value";
            }
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        public string A
        {
            get;
            set;
        }
    }
    public string A
    {
        get;
        set;
    }
    public MyBinding()
    {
        this.Converter = new ValueConverter(A);
    }
}

和XAML(IsEnable是MainWindow类的属性):

<Window x:Class="WpfApplication5.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication5"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBlock>
        <TextBlock.Text>
            <local:MyBinding A="value" Path="IsEnable" RelativeSource="{RelativeSource AncestorType=Window, Mode=FindAncestor}"/>
        </TextBlock.Text>
    </TextBlock>
</Grid>

IsEnable为真时,我愿意使TextBlock显示A,而当IsEnable为假时,我希望使another value显示。

但无论我做什么,我都无法在xaml中设置A的值。当我在.中调试时,它总是null

我在什么地方做错了吗?

如何仅在WPF';s绑定

A属性的值是在调用MyBinding的构造函数后分配的。

您可以在A:的setter中创建转换器

public class MyBinding : Binding
{
    ...
    private string a;
    public string A
    {
        get { return a; }
        set
        {
            a = value;
            Converter = new ValueConverter(a);
        }
    }
}