[英]Double Binding in c# uwp
我有个问题。 我为应用程序创建了2个控件:BottomMenu控件和ResultBox。 ResultBox包含在BottomMenu中,因此顺序如下:页面-> BottomMenu-> ResultBox。 我在ResultBox中创建了一个依赖属性,称为字符串类型的Result。
public ResultBox()
{
this.InitializeComponent();
this.DataContext = this;
}
/// <summary>
/// Property used to store the result of the calculation
/// </summary>
public static readonly DependencyProperty ResultProperty = DependencyProperty.Register(
"Result",
typeof(string),
typeof(ResultBox),
new PropertyMetadata(null)
);
/// <summary>
/// String holding the text assigned to the Result
/// </summary>
public string Result
{
get => (string)GetValue(ResultProperty);
set => SetValue(ResultProperty, value);
}
绑定如下:
<TextBlock Style="{StaticResource DefaultTextBlockStyle}"
Text="{Binding Result}"/>
然后,我在BottomMenu中创建了相同的依赖项属性,以便可以直接从页面进行设置。
public BottomMenu()
{
this.InitializeComponent();
this.DataContext = this;
}
/// <summary>
/// Property used to store the result of the calculation
/// </summary>
public static readonly DependencyProperty ResultProperty = DependencyProperty.Register(
"Result",
typeof(string),
typeof(BottomMenu),
new PropertyMetadata(null)
);
/// <summary>
/// String holding the text assigned to the Result
/// </summary>
public string Result
{
get => (string)GetValue(ResultProperty);
set => SetValue(ResultProperty, value);
}
并绑定:
<local:ResultBox Grid.Row="1" Margin="0 0 0 10"
Result="{Binding Result}"
/>
不幸的是,仅当我在ResultBox的声明中直接输入文本时,该文本才会显示。 当我进行双重装订并将其输入页面时,
<local:BottomMenu Grid.Row="2"
Result="13"/>
它不起作用。 我正在学习绑定,我想知道我在哪里做错了,或者这甚至是做这件事的正确方法。
编辑:ResultBox中的绑定不应包含Source,现在已修复。
您几乎应该永远不要使用this.DataContext = this
; 内部控件。 始终在顶层页面上定义DataContext
,并使其一直沿流程流向每个控件。
所以先删除
this.DataContext = this;
您已经正确定义了依赖项属性Result
。 要将TextBlock
的Text
绑定到它,可以命名控件并使用ElementName
绑定,或者更有效地(仅UWP)使用x:Bind
,如下所示
<TextBlock Style="{StaticResource DefaultTextBlockStyle}" Text="{x:Bind Result, Mode=OneWay}"/>
一样
<local:ResultBox Grid.Row="1" Margin="0 0 0 10" Result="{x:Bind Result, Mode=OneWay}" />
希望这可以帮助。
在这里,而不是设置this.DataContext = this;
,我们应该使用(this.Content as FrameworkElement).DataContext = this;
如下所示:
public BottomMenu()
{
this.InitializeComponent();
(this.Content as FrameworkElement).DataContext = this;
}
public ResultBox()
{
this.InitializeComponent();
(this.Content as FrameworkElement).DataContext = this;
}
在上面的代码中,我们没有设置用户控件的数据上下文,而是在用户控件中设置了第一个孩子的数据上下文。 在此之后, ResultBox
内BottomMenu
可以继承下来从数据上下文BottomMenu
其Result
属性可以适当地设定。 有关更多信息,请参见Jerry Nixon的博客: 演练:XAML用户控件内的双向绑定 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.