OK,WPF的新手,显然需要继续学习更多关于MVVM的知识,我的代码并不是专门设计的,但我确实指定了一个类作为GUI的接口和控制器,而模型代码则驻留在另一组类中。我一直在网上搜索例子和类似于我的问题,其中有很多,但在迷宫中跑了三天后,我请求帮助。
我需要的是一个简单的下拉菜单,其中包含可以动态更新的项目(这是一个与USB设备对话的应用程序,因此无论有多少可用的项目,都应该与设备ID和序列号一起显示(,当前选择的项目应该显示在按钮上(或者我最终使用的下拉菜单的任何实现(。在这个例子中,我只是创建了一个静态列表,但同一列表稍后会在完整的应用程序中动态更新。
到目前为止,我所拥有的似乎是正确的:我将当前选择的设备id字符串显示在按钮上,按下按钮,我将获得所有可用设备的列表(当前选择的装置在列表中冗余显示并不让我感到困扰(。然而,当选择一个项目时,我无法挂接任何事件,因此无法更新按钮中的项目,也无法为此做任何其他事情。
下面是我的XAML。请注意,这是粗略地拼凑在一起的,这里有一些东西毫无意义,比如来自示例的"IsChecked"属性的"IsActive"。最大的问题是,据我所知,ContextMenu中没有Setter属性。资源似乎在做任何事情。。。尝试更改字体大小,但没有成功。当然,真正的大问题是"MyCommand"绑定不起作用,该方法永远不会被调用。
<Label Content="Device Selected:" HorizontalAlignment="Left" Margin="25,22,0,0" VerticalAlignment="Top" Width="124" FontWeight="Bold" FontSize="14" Height="25"/>
<Button x:Name="DeviceSelMenuButton" Content="{Binding DeviceID_and_SN, Mode=TwoWay}" HorizontalAlignment="Left" Height="28" Margin="25,52,0,0" VerticalAlignment="Top" Width="187" FontSize="14" Click="DeviceSelMenuButton_Click">
<Button.ContextMenu>
<ContextMenu ItemsSource="{Binding DeviceID_SN_Collection, Mode=TwoWay}">
<ContextMenu.Resources>
<Style x:Key="SelectDeviceStyle" TargetType="MenuItem">
<Setter Property="Command" Value="{Binding MyCommand}"/>
<Setter Property="CommandTarget" Value="{Binding RelativeSource Self}"/>
<Setter Property="IsChecked" Value="{Binding IsActive}"/>
<Setter Property="IsCheckable" Value="True"/>
<Setter Property="FontSize" Value="14"/>
</Style>
</ContextMenu.Resources>
</ContextMenu>
</Button.ContextMenu>
</Button>
以及MainWindow.xaml.cs:中的代码
public partial class MainWindow : Window
{
CustomDeviceGUI _customDeviceGui = new CustomDeviceGUI();
public MainWindow()
{
InitializeComponent();
this.DataContext = _customDeviceGui;
}
private void DeviceSelMenuButton_Click(object sender, RoutedEventArgs e)
{
// " (sender as Button)" is PlacementTarget
(sender as Button).ContextMenu.IsEnabled = true;
(sender as Button).ContextMenu.PlacementTarget = (sender as Button);
(sender as Button).ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
(sender as Button).ContextMenu.IsOpen = true;
}
private void SomeMethod(object sender, DataTransferEventArgs e)
{
// TODO Somehow get the index of the selected menu item (collection index, 0-based)
// int selIndex = (sender as Button).ContextMenu.Items.IndexOf ??
_customDeviceGui.UpdateDeviceID("RelayPro id updated");
}
}
和GUI代码:
class CustomDeviceGUI : INotifyPropertyChanged
{
// Declare the event
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private string _deviceDisplayString;
private ICommand _updateMenu;
List<string> ControllerDeviceList = new List<string>();
private System.Collections.ObjectModel.ObservableCollection<string> _DeviceID_SN_Collection = new System.Collections.ObjectModel.ObservableCollection<string>();
// CTOR
public CustomDeviceGUI()
{
ControllerDeviceList.Add("CustomDevice Device 1");
ControllerDeviceList.Add("CustomDevice Device 2");
ControllerDeviceList.Add("CustomDevice Device 3");
ControllerDeviceList.Add("CustomDevice Device 6");
UpdateDeviceID(ControllerDeviceList[0]);
}
#region CustomDeviceGUI Properties
public System.Collections.ObjectModel.ObservableCollection<string> DeviceID_SN_Collection
{
get
{
_DeviceID_SN_Collection.Clear();
foreach (string str in ControllerDeviceList)
{
_DeviceID_SN_Collection.Add(str);
}
return _DeviceID_SN_Collection;
}
private set
{
_DeviceID_SN_Collection = value;
}
}
public string DeviceID_and_SN
{
get
{
return _deviceDisplayString;
}
private set
{
_deviceDisplayString = value;
}
}
public ICommand MyCommand
{
get
{
if (_updateMenu == null)
_updateMenu = new MyGuiCommand();
return _updateMenu;
}
}
#endregion
#region Public Methods
public void UpdateDeviceID(string deviceID)
{
this._deviceDisplayString = deviceID;
RaisePropertyChangeEvent("DeviceID_and_SN");
RaisePropertyChangeEvent("DeviceID_SN_Collection");
}
#endregion
protected void RaisePropertyChangeEvent(string name)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
try
{
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
catch (Exception e)
{
// ... TODO Remove this catchall or find specific exceptions
}
}
public class MyGuiCommand : ICommand
{
public void Execute(object parameter)
{
// Debug.WriteLine("Hello, world");
int hmm = 3;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged // was ;
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
} // class CustomDeviceGUI
我所做的所有更改都在XAML中。主要是使用祖先来获得正确的数据上下文。我还切换到了ContextMenu。ItemContainer而不是ContextMenu。资源。
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=DataContext.MyCommand}"/>
</Style>
</ContextMenu.ItemContainerStyle>
Eventough我不确定我认为:
<Setter Property="Command" Value="{Binding MyCommand}"/>
绑定需要RoutedUICommand对象。
编辑:我注意到的另一件事是,您以前没有设置任何命令绑定。像这样:
<Window.CommandBindings>
<CommandBinding Command="MyCommand" Executed="Execute" />
</Window.CommandBindings>
仅举一个例子,您可以将CommandBindings设置为许多其他控件。