4

我有UserControl以下类似:

<UserControl>
    <Expander> 
        <Expander.HeaderTemplate>
            <DataTemplate>
                <Grid HorizontalAlignment="{Binding Path=HorizontalAlignment, RelativeSource={RelativeSource AncestorType={x:Type ContentPresenter}}, Mode=OneWayToSource}">
                    <TextBlock Text="{Binding Path=Service, Mode=TwoWay}"/>
                </Grid>
            </DataTemplate>
        </Expander.HeaderTemplate>            
    </Expander>
</UserControl>

我想将控件的Text属性绑定到我的类的属性,例如:TextBlockUserControl

public string Service
{ get; set; }

我能怎么做?

4

1 回答 1

3

尝试将 设置DataContext为 ,UserControl以便您可以访问属性

在这种情况下,我已将UserControl“UI”(Name="UI")命名为,因此您可以使用绑定ElementName Text="{Binding ElementName=UI, Path=Service}"

例子:

<UserControl x:Class="WpfApplication8.UserControl1"
             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" Name="UI">
    <Expander>
        <Expander.HeaderTemplate>
            <DataTemplate>
                <Grid HorizontalAlignment="{Binding Path=HorizontalAlignment, RelativeSource={RelativeSource AncestorType={x:Type ContentPresenter}}, Mode=OneWayToSource}">
                    <TextBlock Text="{Binding ElementName=UI, Path=Service}" />
                </Grid>
            </DataTemplate>
        </Expander.HeaderTemplate>
    </Expander>
</UserControl>

代码:

我已经实现INotifyPropertyChanged了这将允许在Service字符串更改时更新 UI

public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
    public UserControl1()
    {
        InitializeComponent();
        Service = "Test";
    }

    private string _service;
    public string Service
    {
        get { return _service; }
        set { _service = value; NotifyPropertyChanged("Service"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

结果:

在此处输入图像描述

于 2013-01-18T01:02:33.240 回答