我在UserControl中遇到了DependencyProperty的问题。我的控件公开了两个Dependencyproperties,一个bool和一个字符串。字符串属性有效,但bool没有。我没有错误,但改变都没有反映出来。
我定义了这样的属性:
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中,我绑定到属性,如下所示:
<CheckBox
Name="IncludeSubdirectoriesCheckbox"
IsChecked="{Binding Path=IncludeSubdirectories, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
Include subfolders</CheckBox>
当我使用控件时,我会绑定到这样的属性:
<Controls:DirectorySelect
Directory="{Binding Directory}"
IncludeSubdirectories="{Binding WatchSubDirs}"/>
“目录”是可以正常工作的字符串属性。我以同样的方式绑定它们,但我不能让bool工作。
我哪里出错?
答案 0 :(得分:3)
您可以尝试使用您的用户控件将绑定转换为元素绑定。在此之前,请务必为userControl命名。
然后改变:
IsChecked="{Binding Path=IncludeSubdirectories, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
对于这样的事情:
IsChecked="{Binding Path=IncludeSubdirectories, ElementName="<UserControlName>", Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
您可以执行的另一项健全性检查是确保IncludeSubdirectoriesProperty'的类型所有者是正确的。
答案 1 :(得分: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" />
还可以在工具 - >选项 - &gt;调试 - >输出窗口中更改WPF跟踪设置 到数据绑定=警告
现在查看输出窗口会发生什么
希望这会有所帮助