2011-11-09 26 views
3

我有UserControl中的DependencyProperty問題。我的控件公開了兩個Dependencyproperties,一個布爾和一個字符串。字符串屬性起作用,但布爾沒有。我沒有得到任何的錯誤,但是改變並沒有反映出來。UserControl中的DependencyProperty布爾

我定義屬性是這樣的:

private static readonly DependencyProperty IncludeSubdirectoriesProperty = 
    DependencyProperty.Register(
     "IncludeSubdirectories", 
     typeof(bool), 
     typeof(DirectorySelect), 
     new FrameworkPropertyMetadata(false) { BindsTwoWayByDefault = true } 
     ); 

public bool IncludeSubdirectories 
{ 
    get { return (bool) GetValue(IncludeSubdirectoriesProperty); } 
    set { SetValue(IncludeSubdirectoriesProperty, value); } 
} 

在XAML對於i結合屬性這樣的用戶控制:

<CheckBox 
    Name="IncludeSubdirectoriesCheckbox" 
    IsChecked="{Binding Path=IncludeSubdirectories, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> 
    Include subfolders</CheckBox> 

當我使用控制I結合到屬性如下:

<Controls:DirectorySelect 
    Directory="{Binding Directory}" 
    IncludeSubdirectories="{Binding WatchSubDirs}"/> 

「目錄」是字符串屬性,工作得很好。我以同樣的方式將他們綁定到他們身上,但我無法讓布爾工作。

我哪裏出錯了?

+1

你怎麼看該變化沒有反映出來?你有沒有在'WatchSubDirs'而不是'IncludeSubdirectoriesProperty'本身設置斷點? 'WatchSubDirs' DP還是簡單的屬性? – sll

+0

VS在編譯時不會發出信號,但在Visual Studio的Output窗口上打印日誌信息。總是寫些東西。在所有其他的事情中,你會發現綁定失敗,轉換失敗或其他任何錯誤... – Tigran

+0

我不知道輸出窗口中的狀態消息。這有助於很多:)謝謝。 – SimonHL

回答

3

您可以嘗試將綁定與用戶控件綁定到一個元素綁定。在確定給你的userControl一個名字之前。

然後改變:

 IsChecked="{Binding Path=IncludeSubdirectories, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> 

爲了這樣的事情:

 IsChecked="{Binding Path=IncludeSubdirectories, ElementName="<UserControlName>", Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> 

另一種合理性檢查,您可以執行是確保爲IncludeSubdirectoriesProperty類型所有者是正確的。

+0

這樣做。 問題是,我的用戶控件中的複選框被綁定到datacontext窗口中我使用我的控件,而不是它自己的屬性。錯誤的datacontext與我的usercontrol(Directory)具有相同名稱的屬性,所以綁定意外地使用該屬性,但不包括IncludeSubdirectories。 感謝您的幫助。 – SimonHL

1

嘗試這找出什麼不順心

private static readonly DependencyProperty IncludeSubdirectoriesProperty = 
    DependencyProperty.Register(
     "IncludeSubdirectories", 
     typeof(bool), 
     typeof(DirectorySelect), 
     new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnIncludeSubdirectoriesPropertyChanged)) { BindsTwoWayByDefault = true } 
     ); 

privatestaticvoid OnIncludeSubdirectoriesPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { 
    // make a breakpoint here 
} 

調試綁定

<CheckBox Name="IncludeSubdirectoriesCheckbox" 
      IsChecked="{Binding Path=IncludeSubdirectories, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, diagnostics:PresentationTraceSources.TraceLevel=High}">Include subfolders</CheckBox> 

<Controls:DirectorySelect Directory="{Binding Directory}" IncludeSubdirectories="{Binding WatchSubDirs, diagnostics:PresentationTraceSources.TraceLevel=High}"/> 

必須包括

<Window xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase" /> 

也是在工具 - >選項 - > Debugging->輸出窗口 改變WPF跟蹤設置數據綁定=警告

現在看輸出中的窗口會發生什麼

希望這有助於

相關問題