首页 > 解决方案 > WPF c#相对源祖先数据绑定

问题描述

我在内容控件中有一个带有用户控件的主窗口

<MainWindow Title="MainWindow">
<!-- MainWindows DataContext is set to MainWindowViewModel -->

    <ContentControl Content="{Binding CurrentViewModel}">
        <ContentControl.Resources>
            <DataTemplate DataType="{x:Type viewmodels:ViewModel1}">
                <local:UserControl1/>
            </DataTemplate>
        </ContentControl.Resources>
    <ContentControl/>
<MainWindow/>

和一个带有文本框的用户控件

<UserControl Title="UserControl1">
    <TextBlock Text="{Binding Path=Words}"/>
<UserControl/>

和一个 MainWindowViewModel

public class MainWindowViewModel
{
    private ViewModelBase _currentViewModel;

    public ViewModelBase CurrentViewModel
    {
        get { return _currentViewModel; }
        set 
        { 
            _currentViewModel = value;
            OnPropertyChanged("CurrentViewModel");
        }
    }

    private string _words;

    public string Words
    {
        get { return _words; }
        set 
        { 
            _words = value;
            OnPropertyChanged("Words");
        }
    }
}

如何将文本块文本绑定到 Words 属性?我试过这个,但它不工作......

<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}, Path=DataContext.Words}" />

标签: c#wpf

解决方案


推荐阅读