app*_*yip 13 c# wpf xaml visual-studio
在XAML Designer上,我希望my UserControl(RepositoryContainer)能够填充数据.
我创建了一个命名的文件RepositoryContainerDesignData.xaml(它是在同一文件夹中RepositoryContainer.xaml),并将其设置为d:DataContext给UserControl.
但是,XAML Designer不显示数据,而是显示属性名称.
这是一个最小的例子:
<local:RepositoryContainer xmlns:local="clr-namespace:SystemSpecs.View.UserControls"
Title="My Repository Title"
/>
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
using System.Windows.Controls;
namespace SystemSpecs.View.UserControls
{
public partial class RepositoryContainer : UserControl
{
public string Title { get; set; }
public RepositoryContainer()
{
InitializeComponent();
}
}
}
Run Code Online (Sandbox Code Playgroud)
IsDesignTimeCreatable为true:.vs文件夹RepositoryContainerDesignData.xaml Build Action 是 DesignData我错过了什么吗?
如果我创建一个类(例如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
}
Run Code Online (Sandbox Code Playgroud)
只需将您的Title属性替换为上面的代码,无需添加任何内容即可使其正常工作。SetTitle()仅当您需要对代码中更改的标题做出反应时才需要代码。
我有很久以前创建的 c# 代码片段,可以轻松地创建依赖属性,如果您需要,请告诉我。
| 归档时间: |
|
| 查看次数: |
771 次 |
| 最近记录: |