gpt4 book ai didi

c# - XAML 设计器显示属性名称而不是设计器数据 (d :DataContext) when Binding

转载 作者:可可西里 更新时间:2023-11-01 08:11:26 26 4
gpt4 key购买 nike

上下文

我希望我的 UserControl (RepositoryContainer) 在 XAML Designer 上填充数据。

我创建了一个名为 RepositoryContainerDesignData.xaml 的文件(它与 RepositoryContainer.xaml 位于同一文件夹中)并将其设置为 d:DataContextUserControl

但 XAML 设计器不显示数据,而是显示属性名称。

这是一个最小的例子:

设计数据(RepositoryContainerDesignData.xaml)

<local:RepositoryContainer xmlns:local="clr-namespace:SystemSpecs.View.UserControls"
Title="My Repository Title"
/>

用户控件(RepositoryContainer.xaml)

<UserControl x:Class="SystemSpecs.View.UserControls.RepositoryContainer"
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"
xmlns:local="clr-namespace:SystemSpecs.View.UserControls"
mc:Ignorable="d"
d:DesignHeight="100" d:DesignWidth="500"
d:DataContext="{d:DesignData Source=RepositoryContainerDesignData.xaml}"
DataContext="{Binding RelativeSource={RelativeSource Self}}">

<Grid>
<TextBlock Text="{Binding Path=Title}" FontSize="24" Foreground="White" HorizontalAlignment="Center" />
</Grid>
</UserControl>

代码隐藏

using System.Windows.Controls;

namespace SystemSpecs.View.UserControls
{
public partial class RepositoryContainer : UserControl
{
public string Title { get; set; }

public RepositoryContainer()
{
InitializeComponent();
}
}
}

预期输出:

Expected output

输出:

Output

已经尝试过:

环境信息:

  • Windows 10 专业版 x64
  • Visual Studio Community 2015(版本 14.9.25431.01 更新 3)
  • 微软 .NET 框架 4.6.01586
  • 更多信息请访问 Pastebin RAW保持帖子干净

我错过了什么吗?

附言

如果我创建一个类(例如 public class RepositoryContainerData),创建一个名为 Title 的属性并将此类的实例设置为 d:DataContext (d:DataContext="{d:DesignInstance local:RepositoryContainerData, IsDesignTimeCreatable=True}") 它按预期工作。

最佳答案

您应该在 WPF 用户控件中使用依赖属性,因为它们具有更改通知。

    public static DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(RepositoryContainer), new FrameworkPropertyMetadata(new PropertyChangedCallback(Title_Changed)));

public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}


private static void Title_Changed(DependencyObject o, DependencyPropertyChangedEventArgs args)
{
RepositoryContainer thisClass = (RepositoryContainer)o;
thisClass.SetTitle();
}

private void SetTitle()
{
//Put Instance Title Property Changed code here
}

只需用上面的代码替换您的 Title 属性,无需添加任何内容即可使其正常工作。 SetTitle() 仅当您需要对代码中更改的标题使用react时才需要代码。

我有一个我很久以前创建的 c# 代码片段,可以轻松地制作依赖属性,如果你想要它,请告诉我。

关于c# - XAML 设计器显示属性名称而不是设计器数据 (d :DataContext) when Binding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42096045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com