As the title says I have a WPF application which communicates to a USB relay via a serial port, and (because the COM port changes depending on which USB port you connect it to) I want to have a combobox to select the appropriate one. I have sort of found a way to bind the combobox to a list following the instructions on
this link[
^]. My problem however is twofold: a) I don't really understand how the user choice is reflected back to the code-behind and b) this forces me to change the data context of my XAML which is already set to another source (an object with some simple counters) and thus breaks the old data bindings.
My code would be too big to paste, but if needed I can paste it. The relevant parts however in the XAML are the following:
<StackPanel DataContext="StaticResource Errors">
<Label x:Name="errorDisplayTitle" Content="Total Errors"/>
<StackPanel/>
<ComboBox ItemsSource="{Binding Path=SerialPortParamsEntries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=SerialPortParamsEntry}/>"
So my biggest problem is that the ComboxBox and the StackPanel need to have entirely different DataContext.
For the ComboBox the code behind looks sth like this:
public class ConnectionViewModel : INotifyPropertyChanged
{
public class SerialPortParams
{
public string Name { get; set; }
public SerialPortParams(string name)
{
Name = name;
}
}
public ConnectionViewModel()
{
IList<SerialPortParams> list = new List<SerialPortParams>();
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
list.Add(new SerialPortParams(port));
}
_SerialPortParamsEntries = new CollectionView(list);
}
private readonly CollectionView _SerialPortParamsEntries;
private string _SerialPortParamsEntry;
public CollectionView SerialPortParamsEntries
{
get { return _SerialPortParamsEntries; }
}
public string SerialPortParamsEntry
{
get { return _SerialPortParamsEntry; }
set
{
if (_SerialPortParamsEntry == value) return;
_SerialPortParamsEntry = value;
OnPropertyChanged("SerialPortParamsEntry");
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
The code behind for the StackPanel looks like this
public class Errors : INotifyPropertyChanged
{ private int _totalTouches;
public event PropertyChangedEventHandler PropertyChanged;
public int totalErrors
{
get { return _totalErrors; }
set
{
_totalErrors = value;
NotifyPropertyChanged("totalErrors");
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}