2015-11-05 85 views
0

我有一个自定义绑定像这样:如何在WPF的绑定中仅使用xaml设置值?

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是类主窗口的属性):

<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播放A当IsEnable为真并且当IsEnable为假时显示another value

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

我在某处犯错了吗?

+0

你有一个错字。它的'IsEnabled',而不是'IsEnable'。注意最后的“d”。 –

+0

感谢您的提示。 – Dragon

回答

1

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

你可以在A二传手创建转换器:

public class MyBinding : Binding 
{ 
    ... 

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

谢谢。我知道它是如何工作的。 – Dragon