I want my UserControl
(RepositoryContainer
) to be filled up with data when on XAML Designer.
I created a file named RepositoryContainerDesignData.xaml
(it is in the same folder as the RepositoryContainer.xaml
) and set it as d:DataContext
to the UserControl
.
But instead of displaying the data, XAML Designer displays the property name.
Here's a minimal example:
<local:RepositoryContainer xmlns:local="clr-namespace:SystemSpecs.View.UserControls"
Title="My Repository Title"
/>
<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();
}
}
}
IsDesignTimeCreatable
as true
:.vs
folderRepositoryContainerDesignData.xaml
Build Action
is DesignData
Am I missing something?
If I create a class (e.g. public class RepositoryContainerData
), create a property called Title
and set an instance of this class as d:DataContext
(d:DataContext="{d:DesignInstance local:RepositoryContainerData, IsDesignTimeCreatable=True}"
) it works as expected.
You should use dependency properties in WPF usercontrols as they have change notification.
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
}
Just replace your Title property with the code above, nothing should have to be added to make it work. SetTitle() only needs code if you need to react to the Title changed in code.
I have a c# code snippet that I created a long time ago that can make dependency properties easily, just let me know if you want it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With