2012-07-24 259 views
0

因此,我花了大約兩個小時的時間把我的頭撞到桌子上,試圖將所有我能想到的東西綁定到自定義控件上的屬性,而沒有任何效果。如果我有這樣的事情:WPF數據綁定自定義控件

<Grid Name="Form1"> 
    <mine:SomeControl MyProp="{Binding ElementName=Form1, Path=DataContext.Enable}"/> 
    <Button Click="toggleEnabled_Click"/> 
</Grid> 
public class TestPage : Page 
{ 
    private TestForm _form; 

    public TestPage() 
    { 
     InitializeComponent(); 
     _form = new TestForm(); 
     Form1.DataContext = _form; 
    } 

    public void toggleEnabled_Click(object sender, RoutedEventArgs e) 
    { 
     _form.Enable = !_form.Enable; 
    } 
} 

TESTFORM樣子:

public class TestForm 
{ 
    private bool _enable; 

    public event PropertyChangedEventHandler PropertyChanged; 

    public bool Enable 
    { 
     get { return _enable; } 
     set { _enable = value; OnPropertyChanged("Enable"); } 
    } 

    protected void OnPropertyChanged(string name) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(name)); 
     } 
    } 
} 

而且我的控制是這樣的:

<UserControl> 
    <TextBox Name="TestBox"/> 
</UserControl> 
public class SomeControl : UserControl 
{ 
    public static readonly DependencyProperty MyPropProperty = 
     DependencyProperty.Register("MyProp", typeof(bool), typeof(SomeControl)); 

    public bool MyProp 
    { 
     get { return (bool)GetValue(MyPropProperty); } 
     set { SetValue(MyPropProperty, value); } 
    } 

    public SomeControl() 
    { 
     InitializeComponent(); 
     DependencyPropertyDescriptor.FromProperty(MyPropProperty) 
      .AddValueChanged(this, Enable); 
    } 

    public void Enable(object sender, EventArgs e) 
    { 
     TestBox.IsEnabled = (bool)GetValue(MyPropProperty); 
    } 
} 

當我點擊切換按鈕時絕對沒有任何反應。如果我在Enable回調中放置一個斷點,它將永遠不會被觸發,這是怎麼回事?

回答

2

如果Enabled方法不會做的比設定,你可以刪除它,並綁定TextBox.IsEnabled直接propertou更多:如果你想保持這樣要註冊的方法的特性通過改變回調

<UserControl Name="control"> 
    <TextBox IsEnabled="{Binding MyProp, ElementName=control}"/> 
</UserControl> 

UIPropertyMetadata爲依賴屬性。


而且這種結合是多餘的:

{Binding ElementName=Form1, Path=DataContext.Enable} 

DataContext是繼承的(如果你不將其設置在UserControl(你應該永遠不會做)!),所以你可以只使用:

{Binding Enable} 

此外,如果遇到任何綁定問題:There are ways to debug them

+0

我的印象是'DependencyPropertyDescriptor.FromProperty(MyPropProperty).AddValueChanged(this,Enable);'會導致在該依賴屬性發生任何變化時調用Enable?另外,這是對我實際做的事情的一個簡單的簡化。它恰好代表了這個問題。 – FlyingStreudel 2012-07-24 18:37:41

+0

@FlyingStreudel:哦,我掃描了你的密碼,但錯過了你通過它作爲參考。不要使用描述符,在註冊DP時添加一個更改回調的屬性。 (使用相應的[元數據構造函數](http://msdn.microsoft.com/en-us/library/system.windows.uipropertymetadata.aspx))。 – 2012-07-24 18:41:07

+0

雖然這是靜態的?它如何引用當前實例上的控件? – FlyingStreudel 2012-07-24 18:41:54