我刚开始用C#用MahApps.Metro和Caliburn.Micro编写我的简单应用程序,我遇到了一个问题。我对MVVM模型不太熟悉,所以我试着理解它。我要做的是在单击按钮(单击COM端口并向ComboBox中添加COMs )后将项目填充到combobox中。你能告诉我怎么做吗?这是我的MainView.xaml的一部分:
<WrapPanel Orientation="Horizontal">
<WrapPanel Orientation="Vertical">
<Label Name="SelectCOM" Content="{x:Static r:Translations.SelectCOM}" FontWeight="Bold" FontSize="12" />
<ComboBox Width="235"
x:Name="COMPorts"
SelectedItem="{Binding SelectedPort}" />
</WrapPanel>
<Button Margin="10,0,0,0"
Width="70"
Content="{x:Static r:Translations.Refresh}"
HorizontalAlignment="Right"
cal:Message.Attach="RefreshCOM" />
</WrapPanel>这是我的MainViewModel:
public class MainViewModel : PropertyChangedBase
{
IDevice Device = null;
private string selectedPort;
public void RefreshCOM()
{
string[] ports = SerialPort.GetPortNames();
}
public string SelectedPort
{
get
{
return this.selectedPort;
}
set
{
this.selectedPort = value;
this.NotifyOfPropertyChange(() => this.SelectedPort);
}
}
}发布于 2015-11-22 22:57:47
您需要将COM端口列表“约束”到控件的ItemsSource。
<ComboBox Width="235"
x:Name="COMPorts"
SelectedItem="{Binding SelectedPort}"
ItemsSource="{Binding ComPorts}" />并且不要忘记更新视图模型(添加一个com端口名称的可观察收集 )
public class MainViewModel : PropertyChangedBase
{
// ...
public MainViewModel()
{
ComPorts = new ObservableCollection<string>();
}
public void RefreshCOM()
{
string[] ports = SerialPort.GetPortNames();
foreach(var port in ports)
{
ComPorts.Add(port);
}
}
public ObservableCollection<string> ComPorts {get; private set;}
// ...
}https://stackoverflow.com/questions/33861146
复制相似问题