<UserControl x:Class="blah..my_UserControl "
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:blah."
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<GroupBox x:Name="groupBox" Header="Settings" HorizontalAlignment="Center" Margin="0" VerticalAlignment="Top" RenderTransformOrigin="-0.176,-0.343" Width="503" Height="85">
<Grid>
<ComboBox x:Name="comboBox" ItemsSource="{Binding PortList}" HorizontalAlignment="Left" Margin="0,30,0,0" VerticalAlignment="Top" Width="120" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding}" Width="16" Height="16" Margin="0,2,5,2" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</GroupBox>
</Grid>
</UserControl>
public partial class Child: Base
{
public Child()
{
PortList.add("com1");
}
}
public abstract class Base : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
private ObservableCollection<string> portlist;
public ObservableCollection<string> PortList
{
get { return portlist; }
set
{
portlist = value;
NotifyPropertyChanged("PortList");
}
}
public Base()
{
PortList = new ObservableCollection<string>();
}
}
public partial class my_UserControl : UserControl
{
public my_UserControl(Base base)
{
InitializeComponent();
DataContext = base;
}
}
当我创建一个新的子类时,组合框列表中没有任何内容。它似乎与组合框有关,因为我以完全相同的方式绑定其他几个东西并且它们都起作用。
我在MainWindow.xaml.cs中初始化用户控件和子类
Child child = new Child()
my_userControl control = new my_userControl(child)
//然后将控件添加到mainWindow。
当我点击组合框时,它会抛出此异常。
System.Windows.Data Error: 8 : Cannot save value from target back to source. BindingExpression:Path=IsDropDownOpen; DataItem='ComboBox' (Name='comboBox'); target element is 'ToggleButton' (Name=''); target property is 'IsChecked' (type 'Nullable`1') XamlParseException:'System.Windows.Markup.XamlParseException: Two-way binding requires Path or XPath. ---> System.InvalidOperationException: Two-way binding requires Path or XPath.
at System.Windows.Data.BindingExpression.CreateBindingExpression(DependencyObject d, DependencyProperty dp, Binding binding, BindingExpressionBase parent)
答案 0 :(得分:1)
child
不应该是使用InitializeComponent()
方法的部分视图类。
它应该是一个继承自Base
的简单派生类:
public class child : Base
{
public child()
{
PortList.add("com1");
}
}
然后,您应该将定义了XAML的DataContext
的{{1}}设置为UserControl
的实例:
child
当我点击组合框时,它会抛出此异常。
将绑定模式更改为OneWay或绑定到类的属性:
public partial class my_UserControl : UserControl
{
public my_UserControl()
{
InitializeComponent();
DataContext = new child();
}
}