C# 从contentpresenter中的内容获取附加属性值
我已经创建了一个自定义窗口,其中有一个在资源字典中定义的模板。窗口没有标题栏 我在C# 从contentpresenter中的内容获取附加属性值,c#,wpf,prism,attached-properties,C#,Wpf,Prism,Attached Properties,我已经创建了一个自定义窗口,其中有一个在资源字典中定义的模板。窗口没有标题栏 我在UserControl中设置标题如下: <UserControl x:Class="Something.View" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
UserControl
中设置标题如下:
<UserControl x:Class="Something.View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dsControls="clr-namespace:Something"
Width="400"
dsControls:WindowDetails.Title="Test">
/** Some content **/
</UserControl>
及
另外,更改附加属性的所有者类型
:
- 查看详细信息
公共静态只读从属属性TitleProperty=
DependencyProperty.RegisterAttached(“标题”、typeof(字符串)、typeof(WindowDetails)、new PropertyMetadata(“”)
执行此操作时,未设置属性。但是标签的内容
具有默认的属性值
- 用户控制
公共静态只读从属属性TitleProperty=
DependencyProperty.RegisterAttached(“标题”、typeof(字符串)、typeof(用户控件)、新属性元数据(“”)
当我这样做时,属性被设置,但是标签的内容没有值
问题
如何在我的UserControl
中设置attached属性
,并将其绑定到模板中的标签的内容
提前谢谢
问候
Loetn尝试使用转换器
public class AttchedTitleToTitleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value as FrameworkElement).GetValue(WindowDetails.TitleProperty);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
将其添加到您的资源字典中
:
<local:AttchedTitleToTitleConverter x:Key="titleConverter"/>
在约束中:
<Label Content="{Binding RelativeSource={RelativeSource Self}, Converter={DynamicResource titleConverter}}"/>
希望这有帮助这是您可以做到的:将x:Name
交给您的ContentPresenter
,并在绑定标签时参考它
必须将ownerType
参数设置为所属类的名称,而不是类型,因此在您的情况下将其设置为WindowDetails
是正确的。@Sheridan Yes,但是,属性从未被分配我在UserControl
中定义的值。。。你当然可以做错事。但是,如果您查看MSDN页面上的代码示例,您将看到正在使用的值object2
。。。希望你会同意没有这个名字的字体。@Sheridan是的,我知道。我从没说过你错了。我刚才提到了这一点,因为当我将OwnerType
设置为类时,我无法设置值我知道你没有说我错了。。。我的回答是让你知道,无论它是否有效,这都是正确的做法。你的问题一定出在别的地方了。我必须承认我已经在我的申请中用过了。。哦,好吧,谢谢!:)
<Label Content="{Binding Path=(dsControls:WindowDetails.Title), RelativeSource={RelativeSource Self}}"
FontSize="20" />
public class AttchedTitleToTitleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value as FrameworkElement).GetValue(WindowDetails.TitleProperty);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
<local:AttchedTitleToTitleConverter x:Key="titleConverter"/>
<Label Content="{Binding RelativeSource={RelativeSource Self}, Converter={DynamicResource titleConverter}}"/>