将值绑定到 resourcedictionary 中的文本块

bind value to textblock inside resourcedictionary

我有以下资源字典。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:samplePrjkt"
                    >

    <ToolBar x:Key="MyToolbar" Height="120">
        <!--Template-->
        <GroupBox Header="Template" Style="{StaticResource ToolbarGroup}" Margin="3">
            <StackPanel Grid.Row="1" Orientation="Horizontal">
                <StackPanel Orientation="Vertical" Margin="0,2,0,2">
                    <TextBlock Text="{Binding TextValue}"></TextBlock>
                </StackPanel>
            </StackPanel>
        </GroupBox>
    </ToolBar>
</ResourceDictionary>

resourcedictionay 在以下 WPF 用户控件中使用,如下所示。

<UserControl x:Class="Sampleprjkt.sample.sampleWindow"
        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:Sampleprjkt"            
       >
    <Grid Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="29*"/>
            <RowDefinition Height="107*"/>
        </Grid.RowDefinitions>

        <ContentControl Content="{StaticResource MyToolbar}"/>

    </Grid>
</UserControl>

我正在尝试将值绑定到 WPF 用户控件构造函数中的这个文本块,如下所示

    public partial class SampleWindow : UserControl
    {

        private string _textValue;

        public string TextValue
        {
            get { return _textValue; }
            set
            {
                _textValue = value;

            }
        }

        public SampleWindow()
        {
            InitializeComponent();
            _textValue = "XXXXX";


        }   

    }

但是一旦我 运行 这个,我可以看到 "XXXXX" 值没有设置为 <TextBlock Text="{Binding TextValue}"></TextBlock>,我在这里错过了什么?

您的 ContentControl 缺少一个 DataContext,它是空的。 Binding 将始终引用 DataContext 中的对象,因此 Binding 将找不到 TextValue。

您可以简单地将 UserControl 的 DataContext 设置为其自身:

public SampleWindow()
{
    InitializeComponent();
    _textValue = "XXXXX";

    this.DataContext = this;
}  

DataContext 向下继承到 TextBlock,它现在将显示文本。

您在 XAML 中定义的绑定路径(在您的情况下为 "TextValue")指的是当前 DataContext 的 属性 的名称元素(TextBlock 在你的情况下)或绑定的来源。

这意味着您应该按照@Sharada Gururaj 的建议设置 DataContext

public SampleWindow()
{
    InitializeComponent();
    _textValue = "XXXXX";
    DataContext = this;
}

...或指定绑定的明确来源:

<TextBlock Text="{Binding Path=TextValue, Source={RelativeSource AncestorType=UserControl}}"></TextBlock>