【发布时间】:2015-11-30 07:13:42
【问题描述】:
有 2 个 XAML,为什么第二个有效,而第一个无效?
cs:
public partial class myClass: Window
{
public static DependencyProperty RoutersPortsViewProperty = DependencyProperty.Register("RoutersPortsView", typeof(DataView), typeof(myClass));
public myClass()
{
DataTable MyTable = new DataTable();
/*here fill MyTable*/
SetValue(RoutersPortsViewProperty, new DataView(MyTable);
InitializeComponent();
}
/*there other code for class*/
}
XAML 不起作用:
<Window Name="myName" x:Class="myClass">
<DataGrid>
<DataGrid.Columns>
<DataGridComboBoxColumn DisplayMemberPath="DisplayString"
SelectedValuePath="id"
SelectedValueBinding="{Binding Path=NWPatchPanelID, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}"
ItemsSource="{Binding Path=RoutersPortsView, ElementName=myName}"/>
</DataGrid.Columns>
</DataGrid>
</Window>
错误:
System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。 BindingExpression:Path=RoutersPortsView;数据项=空;目标元素 是'DataGridComboBoxColumn' (HashCode=11022751);目标属性是 “ItemsSource”(类型“IEnumerable”)
XAML 工作:
<Window Name="myName" x:Class="myClass">
<DataGrid>
<DataGrid.Columns>
<DataGridComboBoxColumn DisplayMemberPath="DisplayString"
SelectedValuePath="id"
SelectedValueBinding="{Binding Path=NWPatchPanelID, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}">
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=RoutersPortsView, ElementName=myName}"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
</Window>
【问题讨论】:
-
您是否为 RoutersPortsViewProperty 创建了包装器?
-
@Spawn 当然!然后有第二个选项也没有用=)
-
尝试设置InitializeComponent()后的值;
-
@ДмитрийЧистик 在InitializeComponent之后的构造函数中设置window的DataContext为this.DataContext = this,itemsssource为ItemsSource="{Binding Path=RoutersPortsView}。
-
另请注意,静态字段只能在静态构造函数中初始化。