【发布时间】:2013-07-30 06:31:12
【问题描述】:
我需要帮助!
我已经构建了一个自定义控件并添加了一个DependencyProperty 类型:
Dictionary<string,int>
并从控件所在的 XAML 中,我执行数据绑定以绑定到控件外部的字典。
这里有一些代码 sn-ps: 持有自定义控件的控件的视图模型
private Dictionary<string, int> _wordsList;
public Dictionary<string, int> WordsList
{
get
{
return _wordsList;
}
set
{
_wordsList = value;
RaisePropertyChanged("WordsList");
}
}
public WordsViewModel()
{
//CalculateWordsDictionary returns a dictionary<string,int>
WordsList = CalculateWordsDictionary(texts);
}
XAML:
<local:MyControl WordsList="{Binding Path=WordsList}" />
自定义控件的代码:
public Dictionary<string, int> WordsList
{
get { return (Dictionary<string, int>)GetValue(WordsListProperty); }
set { SetValue(WordsListProperty, value); }
}
// Using a DependencyProperty as the backing store for WordsList. This enables animation, styling, binding, etc...
public static readonly DependencyProperty WordsListProperty =
DependencyProperty.Register("WordsList", typeof(Dictionary<string, int>), typeof(MyControl), new PropertyMetadata(new Dictionary<string, int>()));
我在DependencyProperty 的集合上设置了一个断点,但它永远不会到达这个点。
我只是不知道为什么这不起作用......或者也许有其他方法可以将字典传递给控件?
顺便说一句 我正在使用 MVVM Light
【问题讨论】:
-
能否为 DependencyProperty 添加 Propertychanged 回调并检查,public static DependencyProperty FirstProperty = DependencyProperty.Register("First", typeof(string), typeof(MyType), new FrameworkPropertyMetadata( false, new PropertyChangedCallback(OnFirstPropertyChanged) )));私有静态无效 OnFirstPropertyChanged(DependencyObject 发送者,DependencyPropertyChangedEventArgs e){ PropertyChangedEventHandler h = PropertyChanged; if (h != null) { h(sender, new PropertyChangedEventArgs("Second")); } }
-
如果我理解正确,我应该尝试在控件后面的代码中捕获属性更改事件...我试图这样做:(stackoverflow.com/questions/12798909/…)没有运气
-
那么你的绑定应该有问题。定义转换器并在转换器中放置断点,并确保您的绑定没有任何问题。您还可以检查输出窗口是否存在绑定错误
-
当在 XAML 中和/或通过绑定设置属性时,不会调用
WordsList设置器。有关说明,请参阅here。您必须通过属性元数据注册PropertyChangedCallback。 -
MyControl的DataContext是否设置在任何地方?
标签: c# wpf data-binding mvvm dependency-properties