【发布时间】:2018-02-09 13:47:28
【问题描述】:
我不确定我在这里做错了什么。
可以说,我有两个用户控件BoxA和BoxB。两者都有一个名为 Text
BoxB 包装了具有常规 TextBox 的 BoxA。
绑定应该像这样 BoxB.Text BoxA.Text TextBox.Text
Xaml BoxA:
<UserControl x:Class="SandBoxWpf.BoxA"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></TextBox>
</UserControl>
Xaml BoxB:
<UserControl x:Class="SandBoxWpf.BoxB"
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:SandBoxWpf"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<local:BoxA Text="{Binding Text, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></local:BoxA>
</UserControl>
BoxA 和 BoxB 的代码隐藏
using System.Windows;
using System.Windows.Controls;
namespace SandBoxWpf
{
/// <summary>
/// Interaktionslogik für BoxA.xaml
/// </summary>
public partial class BoxX : UserControl
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(BoxX),
new PropertyMetadata(default(string)));
public string Text
{
get => (string) GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public BoxX()
{
InitializeComponent();
}
}
}
主窗口
<Window x:Class="SandBoxWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SandBoxWpf"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<local:BoxB Width="100" Height="20" Text="{Binding Title}"></local:BoxB>
</Grid>
</Window>
只要我在 BoxB 中输入内容,我就会收到 StackoverflowException。 如果我删除 Mode=TwoWay 或 UpdateSourceTrigger,StackOverflow 就会消失,但绑定也不起作用。
【问题讨论】:
-
听起来像是某种形式的无限递归。你能告诉我们你的变更通知代码吗?有一种常见的递归情况(未检测到设置相同的值)。
-
@Christopher 除了依赖属性之外没有代码。
-
当我使用
UserControl时,我通常在InitlialiseComponents后面的代码中设置DataContext,试试看它是否有效。顺便说一句,我认为是这个:DataContext="{Binding RelativeSource={RelativeSource Self}}"导致了这个问题。 -
@XAMlMAX 同样的问题。但是,当我使用代码而不是 Xaml 进行绑定时,它会起作用。
-
你能把它上传到 git repo 吗?我想在我的机器上重现它。你在两个 UC 上都这样做了吗?盒子A和盒子B?