[英]How to access Textblock in DataTemplate in ribbon in WPF?
我是使用 WPF 的新手,我搜索了一整天,但没有找到任何可以将其应用于可能应用程序的答案。
我有一个菜单功能区,但我想通过我的.cs
代码设置功能区的标题。 我的问题是我无法访问<Ribbon.TitleTemplate>
中的文本块。
这是我的 XAML 代码
<Ribbon x:Name="Ribbon">
<Ribbon.TitleTemplate>
<DataTemplate >
<TextBlock x:Name="FrontPageTitle" TextAlignment="Center" HorizontalAlignment="Stretch" Width="{Binding ElementName=RibbonWindow, Path=ActualWidth}">
<TextBlock.Effect>
<DropShadowEffect ShadowDepth="0" Color="MintCream " BlurRadius="10" />
</TextBlock.Effect>
</TextBlock>
</DataTemplate>
</Ribbon.TitleTemplate>
<Ribbon.HelpPaneContent>
<RibbonButton SmallImageSource="pack://application:,,,/MYSEP;component/Images/window.png" />
</Ribbon.HelpPaneContent>
<Ribbon.QuickAccessToolBar>
<RibbonQuickAccessToolBar>
<RibbonButton x:Name="QATButton1"
SmallImageSource="pack://application:,,,/MYSEP;component/Images/window.png" />
<RibbonButton x:Name="QATButton2"
SmallImageSource="pack://application:,,,/MYSEP;component/Images/window.png" />
</RibbonQuickAccessToolBar>
</Ribbon.QuickAccessToolBar>
</Ribbon>
这是我的 C# 代码
public FrontPage()
{
InitializeComponent();
mypSepProject = (Project)App.Current.Properties["myp_projects"];
FrontPageTitle.Text = mypSepProject.ProjectName;
CreateRecentMenu();
SetTreeViewMenu();
ShowChildeWindow("Process Data");
}
但是当前页面中不存在FrontPageTitle
。 但是当我将textblock
放在DataTemplate
之外时,它已经可以读取FrontPageTitle
了。 我希望你们能帮助我。 谢谢你。
您必须使用数据绑定。 为此,将DepndencyProperty
添加到FrontPage
class 例如, Title
并将Ribbon.TitleTemplate
的TextBlock.Text
绑定到它。
如果FrontPage
是Page
,您可以改用继承的Page.Title
属性:
FrontPage.xaml.cs
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register(
"Title",
typeof(string),
typeof(FrontPage),
new PropertyMetadata(default(string)));
public string Title
{
get => (string) GetValue(FrontPage.TitleProperty);
set => SetValue(FrontPage.TitleProperty, value);
}
public FrontPage()
{
InitializeComponent();
mypSepProject = (Project)App.Current.Properties["myp_projects"];
this.Title = mypSepProject.ProjectName;
}
FrontPage.xaml
<Ribbon x:Name="Ribbon">
<Ribbon.TitleTemplate>
<DataTemplate>
<TextBlock x:Name="FrontPageTitle"
Text="{Binding RelativeSource={RelativeSource AncestorType=FrontPage}, Path=Title}"" />
</DataTemplate>
</Ribbon.TitleTemplate>
</Ribbon>
我迟到了半个小时:-)
将此添加到您的FrontPageTitle
TextBlock
:
Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Ribbon}}, Path=Title}"
在代码中你可以这样做:
Ribbon.Title = "ABC";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.