简体   繁体   中英

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

I have a custom Binding like this:

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);
    }
}

and the XAML(IsEnable is a property of 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>

I am willing to make the TextBlock show A when IsEnable is true and show another value when IsEnable is false.

But Whatever I do, I can not set value of A in the xaml. It always be null when I debug in.

Did I wrong in someplace?

The value of the A property is assigned after the constructor of MyBinding has been called.

You could create the Converter in the setter of A :

public class MyBinding : Binding
{
    ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM