[英]MVVM listbox item contextmenu
我在綁定列表框項的上下文菜單時遇到問題。 構建后我的上下文菜單不會顯示任何項目。 我已經搜索了很多,但沒有任何積極的結果。 上下文菜單仍然是空的。 你知道我的問題有什么解決方案嗎?
感謝幫助。
列表框:
<ListBox Name="uxTrendListBox" ItemsSource="{Binding SignalGroup.Trends}" SelectedIndex="0" DisplayMemberPath="TrendName" SelectedValue="{Binding SelectedTrend}" FontSize="14" FontWeight="Normal" BorderThickness="0" Foreground="white" DockPanel.Dock="Top" Margin="10" Background="#FF5B5A5A">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu ItemsSource="{Binding CommandList}">
<ContextMenu.ItemTemplate >
<DataTemplate>
<MenuItem Header="{Binding Displayname}" Command="{Binding ContextMenuCommand}" />
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox >
命令列表:
private ObservableCollection<ContextMenuAction> commandList = new ObservableCollection<ContextMenuAction>();
public ObservableCollection<ContextMenuAction> CommandList
{
get
{
return commandList;
}
set
{
Set(ref commandList, value);
}
}
填充 ViewModel 類構造函數的命令列表:
CommandList.Add(new ContextMenuAction
{
Displayname = "Rename trend",
ContextMenuCommand = TrendRenameCommand
});
CommandList.Add(new ContextMenuAction
{
Displayname = "Remove trend",
ContextMenuCommand = TrendRemoveCommand
});
ContextMenuAction 類:
public class ContextMenuAction : INotifyPropertyChanged
{
private string displayName;
public string Displayname
{
get { return displayName; }
set
{
displayName = value;
PropertyChanged(this, new PropertyChangedEventArgs("Displayname"));
}
}
private ICommand contextMenuCommand;
public ICommand ContextMenuCommand
{
get { return contextMenuCommand; }
set
{
contextMenuCommand = value;
PropertyChanged(this, new PropertyChangedEventArgs("ContextMenuCommand"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
通過按f5啟動調試應用程序。 導航到頁面並顯示上下文菜單以在調試時重現錯誤
檢查輸出窗口中是否存在綁定錯誤( Menu->Debug->Windows->Output
)。 如果綁定有錯誤,則應在此處看到
您在哪里定義CommandList
屬性? 它應該在您的“趨勢”類中或您所說的任何類中
在字段初始值設定項中創建可觀察集合的實例時,為什么在CommandList
屬性上具有公共設置器? 這可能無法解決問題,但是通常您只添加或刪除集合中的項目,或者不修改集合,而是始終設置集合的新實例。 您的課程允許同時使用,這聞起來很香
謝謝,將CommandList移到我的趨勢模型可以解決它!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.