我在我的项目中创建了userControl Node,其定义如下:
<UserControl x:Class="ProjectCrow.Node"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ProjectCrow"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Border Name="border" BorderBrush="Black" BorderThickness="1">
<DockPanel LastChildFill="True" Background="AliceBlue" Height="45" Canvas.Top="90" Width="160" MouseRightButtonDown="OnNodeDeselect" MouseLeftButtonDown="OnNodeClick" >
<Border BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Left">
<Image Name="img" />
</Border>
<Border BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Bottom" Height="10" >
<TextBlock Name="protocol" VerticalAlignment="Center" Background="Gold" TextAlignment="Center" TextWrapping="Wrap"> FFI
</TextBlock>
</Border>
<Border BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Top">
<TextBlock Name="nodeName" VerticalAlignment="Center" TextAlignment="Center" TextWrapping="Wrap">UNIT
</TextBlock>
</Border>
</DockPanel>
</Border>
我在我的应用程序中多次使用它。基本上它表示一个节点,具有已定义的IP和端口,您可以从中获取一些数据。
我创建了一个组合框,供用户用来选择从哪个源节点收集数据。我使用数据绑定来获取当前可用节点的列表。
sourcesBox.SetBinding(ComboBox.ItemsSourceProperty, new Binding() { Source = MainUI.mainWindow.sources});
sourcesBox.DisplayMemberPath = "NameString";
sourcesBox.SelectedValuePath = "NameString";
MainUI.mainWindow.Sources
为public ObservableCollection<Node> sources;
我还将为您提供部分Node类的实现
public partial class Node : UserControl
{
bool selected = false;
string name;
public string NameString
{
get { return name; }
set { if (name != value)
{
name = value;
NotifyPropertyChanged("NameString");
}
}
}
public virtual event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(params string[] propertyNames)
{
if (PropertyChanged != null)
{
foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
PropertyChanged(this, new PropertyChangedEventArgs("HasError"));
}
}
public Node()
{
InitializeComponent();
}
ComboBox正确显示当前可用的所有可能节点,但如果我选择了某些内容,则不会显示SelectedValue。
我该如何解决这个问题?
答案 0 :(得分:0)
您应该能够使用SelectedValue属性将所选数据对象绑定到ComboBox(我相信SelectedItem属性是只读的)。如果必须在代码中设置此绑定,则可以这样做:
ComboBox Box = new ComboBox();
Binding b = new Binding()
{
Source = YourViewModel,
Path = new PropertyPath("YourViewModelProperty"),
Mode = BindingMode.TwoWay
};
Box.SetBinding(ComboBox.SelectedValueProperty, b);
或者在XAML(我的首选方法)中:
<ComboBox SelectedValue="{Binding YourViewModelProperty, Mode=TwoWay}">
<ComboBox.ItemTemplate>
<DataTemplate>
<!--Your UserControl goes here-->
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>