2
我创建了一个自定义控件,其中包含用于数据绑定的依赖项属性。 然后应将绑定的值显示在文本框中。 此绑定正常工作。WPF:无法绑定到自定义控件的依赖项属性
当我实现我的自定义控件时,会发生此问题。网格的数据上下文是一个简单的视图模型,它包含一个用于绑定的String属性。
- 如果我将此属性绑定到标准wpf控件文本框一切正常。
- 如果我将属性绑定到我的自定义控件,则不会发生任何事情。
一些调试后我发现SampleText中搜索CustomControl。当然它并不存在。 为什么我的财产搜查CustomControl,当它在方案1
<Window x:Class="SampleApplicatoin.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:SampleApplication"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.DataContext>
<controls:ViewModel/>
</Grid.DataContext>
<TextBox Text="{Binding SampleText}"/>
<controls:CustomControl TextBoxText="{Binding SampleText}"/>
</Grid>
</Window>
发生下面的自定义控件的XAML代码没有从的DataContext拍摄。 我用的DataContext =自从后面的代码获得依赖属性:
<UserControl x:Class="SampleApplication.CustomControl"
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}}">
<Grid>
<TextBox HorizontalAlignment="Left" Height="23" Margin="87,133,0,0" TextWrapping="Wrap" Text="{Binding TextBoxText}" VerticalAlignment="Top" Width="120"/>
</Grid>
</UserControl>
的xaml.cs文件只包含依赖属性:
public partial class CustomControl : UserControl
{
public static readonly DependencyProperty TextBoxTextProperty = DependencyProperty.Register("TextBoxText", typeof (String), typeof (CustomControl), new PropertyMetadata(default(String)));
public CustomControl()
{
InitializeComponent();
}
public String TextBoxText
{
get { return (String) GetValue(TextBoxTextProperty); }
set { SetValue(TextBoxTextProperty, value); }
}
}
感谢有这方面的帮助。现在真的让我发疯。
编辑:
我只是过来两个可能的解决方案:
这里第一(这为我的作品):
<!-- Give that child a name ... -->
<controls:ViewModel x:Name="viewModel"/>
<!-- ... and set it as ElementName -->
<controls:CustomControl TextBoxText="{Binding SampleText, ElementName=viewModel}"/>
第二个。这在我的情况下不起作用。我不知道为什么:
<controls:CustomControl TextBoxText="{Binding SampleText, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type controls:ViewModel}}}"/>
<!-- or -->
<controls:CustomControl TextBoxText="{Binding SampleText, RelativeSource={RelativeSource FindAncestor, AncestorType=controls:ViewModel}}"/>