我正在准备Custom UserControl,它将位于DataGrid
。此控件的DataContext
将是行ID(来自数据库)和位于ComboBox
下的DataGrid
的值。
这是我在DataGrid
中嵌入我的控件的方式:
<datagrid:DataGridTemplateColumn>
<datagrid:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<nmspc:MyControl IdT="{Binding id}" BValue="{Binding SelectedValue, ElementName=MyComboBox}" />
</DataTemplate>
</datagrid:DataGridTemplateColumn.CellTemplate>
</datagrid:DataGridTemplateColumn>
我想绑定的值是id和MyComboBox的选择。 这就是MyControl Code背后的样子:
public static readonly DependencyProperty IdTProperty = DependencyProperty.Register("IdT", typeof(int), typeof(MyControl), new PropertyMetadata(IdTChanged));
private static void IdTChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//BoxResult obj = d as MyControl;
MessageBox.Show(e.NewValue.ToString());
//obj.IdT = (int)e.NewValue;
}
public int IdT
{
set {SetValue(IdTProperty, value); }
get {return (int)GetValue(TEIdProperty); }
}
public static readonly DependencyProperty BValueProperty = DependencyProperty.Register("BValue", typeof(string), typeof(MyControl), new PropertyMetadata(IdTChanged));
private static void BValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//BoxResult obj = d as MyControl;
MessageBox.Show(e.NewValue.ToString());
//obj.IdT = (string)e.NewValue;
}
public int BValue
{
set {SetValue(BValueProperty, value); }
get {return (int)GetValue(BValueProperty); }
}
绑定机制无法使用我的代码。我期待将调用IdTChanged和BValueChanged的回调,但他们不会。 编写此代码我基于this。提前感谢所有的消遣。
此致 的Pawel
修改
这是查看调试输出的方式:
System.Windows.Data Error: BindingExpression path error: 'id' property not found on 'My.MyControls.MyView.DataParams' 'My.MyControls.MyView.DataParams' (HashCode=42491497). BindingExpression: Path='id' DataItem='My.MyControls.MyView.DataParams' (HashCode=42491497); target element is 'My.MyControls.MyView.MyControl' (Name=''); target property is 'IdT' (type 'System.Int32')..
System.Windows.Data Error: BindingExpression path error: 'id' property not found on '852' 'System.Int32' (HashCode=852). BindingExpression: Path='id' DataItem='My.MyControls.MyView.DataParams' (HashCode=42491497); target element is 'My.MyControls.MyView.MyControl' (Name=''); target property is 'IdT' (type 'System.Int32')..
我发现这是RelativeSource的问题。所以在绑定中我设置了这个值:
RelativeSource={RelativeSource TemplatedParent}
BindingExpression的问题消失了,但它仍然不起作用(未显示IdTChanged中的MessageBox)。
一些建议?