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

时间:2015-11-05 11:01:57

标签: c# wpf xaml 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是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>

我愿意在TextBlock为真的情况下制作IsEnable节目A,并在another value为假时显示IsEnable

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

在某个地方我错了吗?

1 个答案:

答案 0 :(得分:1)

在调用MyBinding的构造函数之后,为A属性赋值

您可以在A

的设置器中创建转换器
public class MyBinding : Binding
{
    ...

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