2009-08-20 3 views
2

私は、このXAMLを持っている:WPFコントロールをコードの背後にバインドするにはどうすればいいですか?

<Window x:Class="WpfBindToCodeBehind.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300" 
    Loaded="Window_Loaded"> 
    <StackPanel Orientation="Vertical"> 
     <Button Name="ToggleExpand" Click="ToggleExpand_Click">Toggle Expander</Button> 
     <Expander Name="Expander" 
        Header="Don't click me, click the button!" 
        IsExpanded="{Binding RelativeSource={RelativeSource Self},Path=MayExpand}"> 
      <TextBlock Text="{Binding}"/> 
     </Expander> 
    </StackPanel> 
</Window> 

これは背後にあるコードです:

public partial class Window1 : Window,INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 

     public Window1() 
     { 
      InitializeComponent(); 
     } 

     private void ToggleExpand_Click(object sender, RoutedEventArgs e) 
     { 
      MayExpand = !mayExpand; 
     } 

     private void Window_Loaded(object sender, RoutedEventArgs e) 
     { 
      Expander.DataContext = "Show me"; 
     } 

     private bool mayExpand; 
     public bool MayExpand 
     { 
      get { return mayExpand; } 
      set 
      { 
       mayExpand = value; 
       if (PropertyChanged != null) 
        PropertyChanged(this, new PropertyChangedEventArgs("MayExpand")); 
      } 
     } 
    } 

isExpandedとしてプロパティのバインディング式が機能していません。このコードは簡素化されていますが、実際にはエクスパンダのバインディングは親コントロールのデータインターフェイスを通じて既に設定されています。
コードのプロパティにIsExpandedプロパティをバインドする方法はありますか。
コードのメソッドの結果にバインドできますか?

+0

あなたがいない直接メソッド、同じクラスかにバインドすることはできません。メソッドをプロパティ呼び出しとしてカプセル化するか、値コンバーターを使用するか、制限を回避する必要があります。 –

答えて

10

結合源はRelativeSource.Selfである。つまり、ソースはWindowではなくExpanderです。このような何かが動作します:

IsExpanded="{Binding MayExpand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}" 

また、物事を単純化するために名前を使用することができます。

<Window x:Name="_root"> 
    <Expander IsExpanded="{Binding MayExpand, ElementName=_root}"/> 
+0

すごく、ありがとう! – Dabblernl

関連する問題