如何仅在 WPF 的绑定中使用 xaml 设置值?

How can I set the value using xaml only in WPF's Binding?

我有这样的自定义绑定:

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 是 class 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>

我愿意让 TextBlockIsEnable 为真时显示 A,在 IsEnable 为假时显示 another value

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

我是不是哪里错了?

A 属性 的值在 调用 MyBinding 的构造函数后 赋值。

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

public class MyBinding : Binding
{
    ...

    private string a;
    public string A
    {
        get { return a; }
        set
        {
            a = value;
            Converter = new ValueConverter(a);
        }
    }
}