2013-07-30 49 views
0

我需要一些帮助!数据绑定字典<string,int>到依赖属性

我有建立一个自定义控制和引用加到它类型的DependencyProperty

Dictionary<string,int> 

并从那里控制被保持在XAML我做数据绑定到绑定到词典的控制之外。

这里有一些代码片段:谁持有自定义控件控制的 视图模型

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的集合上设置了一个断点从来没有达到这一点。

我只是不知道为什么这不起作用......或者也许有其他方式将字典传递给控件?

BTW 我使用MVVM光

+0

你可以添加的PropertyChanged回调的DependencyProperty和检查,公共静态的DependencyProperty FirstProperty = DependencyProperty.Register( “第一”, typeof运算(字符串), typeof运算(的MyType), 新FrameworkPropertyMetadata( false, new PropertyChangedCallback(OnFirstPropertyChanged))); private static void OnFirstPropertyChanged( DependencyObject sender,DependencyPropertyChangedEventArgs e) PropertyChangedEventHandler h = PropertyChanged; (发送方,新的PropertyChangedEventArgs(“Second”)); } } – Sivakumar

+0

如果我理解正确,我应该尝试在控件背后的代码中捕获属性已更改的事件...我试图这样做:(http:// stackoverflow。com/questions/12798909/how-to-catch-a-property-changed-event-after-binding)没有运气 –

+0

那么它应该是你的绑定问题。定义转换器并在转换器中放置断点,并确保您的绑定没有任何问题。您也可以检查输出窗口是否存在绑定错误 – Sivakumar

回答

1

你没有张贴:)什么是您的用户控件内结合重要的东西?你必须使用某种“本地绑定”,以便你的MyControl绑定到它的依赖属性。您可以使用绑定的ElementName像这样:

编辑:这里是

<MyControl x:Name=uc> 
    <ContentControl Content="{Binding ElementName=uc, Path=WordsList}"/> 
+0

我发布的实际定义是自定义控件位于用户控件的xaml中。“local”只是自定义控件的名称空间,因此我可以通过xaml访问它。我现在更改了名称,以便它更清晰:

+0

您不了解我,重要的代码是您的usercontrol的xaml定义。这是我的代码片段。并且因为我不知道Wordslist在您的用户控件中绑定的位置,所以我将它绑定到ContentControl。你绑定到你的用户控件是正确的,但那不是问题。至少你可以告诉我们你想用你的依赖属性实现什么 – blindmeis

+0

我有一个用户控件,它在xaml中保存了一个自定义控件。我想构建一个自定义标签云控件,通过依赖项属性获取Dictionary (该单词及其出现次数)。所以我真的不明白哟建议解决这个问题。 –

0

定名为MyControl的用户控件的代码(只是一个片段)!!!!!

所有评论一起在那里被一个DataContext定义我的问题

,我彻底删除它。我还注册了房产改变回调

作为魅力!

感谢所有

+0

随时在这里发布你的糟糕和好的代码 – blindmeis