我在WPF中写了一个UserControl来实现" SerialPort"来自" System.IO.Ports"它包含一些按钮和一个ComboBox。
它有一些代码可以打开端口,关闭端口以及从PC上获取所有端口。
以下是我的XAML的一部分:
<Grid>
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center">
<TextBlock Text="Choose COM:"
VerticalAlignment="Center"
Margin="10,0"/>
<ComboBox Name="ComboBoxPorts"
Height="25"
Width="80" />
</StackPanel>
</Grid>
同样在这个XAML背后的代码中我有一个有效的功能,可以从PC获取所有端口,并且应该在我的ComboBox中填充可用的COM端口。
编辑:
public partial class Communication : UserControl
{
public SerialPort comPort = new SerialPort();
public ObservableCollection<string> Ports
{
get
{
return (ObservableCollection<String>)GetValue(OCProperty);
}
set
{
SetValue(OCProperty, value);
}
}
public Communication()
{
InitializeComponent();
}
public void GetPortNames()
{
int num;
this.ports = new ObservableCollection<string>();
string[] port_Names = SerialPort.GetPortNames().OrderBy(a => a.Length > 3 && int.TryParse(a.Substring(3), out num) ? num : 0).ToArray();
foreach (string port in port_Names)
this.ports.Add(port);
this.DataContext = this;
ComboBoxPorts.ItemsSource = this.ports;
ComboBoxPorts.SelectedItem = this.ports.FirstOrDefault(); // object to show on comboBox
}
public static readonly DependencyProperty OCProperty =
DependencyProperty.Register("Ports", typeof(ObservableCollection<String>), typeof(Communication));
在我的MainWindow中,我调用了UserControl元素,然后在加载窗口后,ComboBox仍然为空而没有任何字符串。 我怎么能让我在我的UserControl中定义的ComboBox中看到COM端口?
主窗口代码:
编辑:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
My MainWindow XAML:
编辑:
<Window x:Class="MyLabratory.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:MyProject ="clr-namespace:MyLabratory"
Title="MainWindow" Height="350" Width="525">
<Grid>
<MyProject:Communication />
</Grid>
感谢您的帮助!
答案 0 :(得分:1)
您必须将用户控件添加到可视树中,您只是实例化它,但您还需要添加到布局控件,如Grid
。
而不是以编程方式创建控件:
Communication communicator = new Communication();
我会在Xaml中创建它:
<Communication Name="communicator"/>
答案 1 :(得分:1)
首先,您应该为项目使用MVVM
模式,而不是像获取端口名称那样完成所有逻辑,并且应该从视图模型中填充ComboBox
。
对于您的情况,请使用以下代码:
public partial class Communication : UserControl
{
public SerialPort comPort = new SerialPort();
public ObservableCollection<string> Ports {get;set;}
public Communication()
{
InitializeComponent();
}
public void GetPortNames()
{
int num;
this.Ports= new ObservableCollection<string>();
string[] port_Names = SerialPort.GetPortNames().OrderBy(a => a.Length > 3 && int.TryParse(a.Substring(3), out num) ? num : 0).ToArray();
foreach (string port in port_Names)
this.Ports.Add(port);
this.DataContext=this;
ComboBoxPorts.ItemsSource = this.Ports;
ComboBoxPorts.SelectedItem = this.Ports.FirstOrDefault(); // object to show on comboBox
}
}
创建ObservableCollection<string>
类型的属性,该属性将作为ComboBox
的项目来源。在ObservableCollection
添加/删除项目时,UI会更新。