在我的UserConterl中。無法在元素ResourceDictionary中綁定DataContext
<UserControl.Resources >
<ResourceDictionary >
<ContextMenu x:Key="MyContextMenu " >
<MenuItem Header="{Binding Header}">
</ContextMenu >
<HierarchicalDataTemplate x:Key="MyTemplate">
<TextBlock x:Key="MyTextBlock" Text = {Binding Header} ContextMenu="{StaticResource MyContextMenu }"/>
</HierarchicalDataTemplate >
</ResourceDictionary >
</UserControl.Resources>
<TreeView ItemTemplate="{StaticResource MyTemplate}" ItemsSource="{Binding MySources}" >
上面的代碼在xaml中。代碼在UserControl xaml的.cs中。
public MyUserControl()
{
InitializeComponent();
this.DataContext = new MyViewModel();
}
public class MyViewModel: ViewModelBase
{
public string Header {get; set;}
public List<string> MySources \\ Has been assigned
}
預期的結果是顯示領域頭當我點擊rightbutton.Actually,在彈出菜單empty.I發現文本菜單沒有綁定的DataContext。我該怎麼辦? 謝謝!
如果你在調試模式下運行時,可以檢查輸出窗口任何約束力的錯誤。 – Pravin 2015-03-31 10:35:10
只需檢查一下非常明顯的內容:這是你試圖運行的代碼的複製/粘貼?當您的Header屬性位於DataSheetManagerViewModel中時,您似乎已將您的UserControl鏈接到名爲MyViewModel的東西。 – goobering 2015-03-31 10:44:12
@Pravin no ..我不知道ResourceDictionary中的DataContext是否會繼承UserControl。 – spark 2015-03-31 10:45:36