user8162574
user8162574

Reputation:

WPF Custom Control Not Displaying Data

Here I have my custom control:

xaml:

<UserControl x:Class="Tasks.Assets.Objects.Card"
         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:Tasks.Assets.Objects"
         mc:Ignorable="d" 
         d:DesignHeight="200" d:DesignWidth="150">
<Grid>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="1*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="135"/>
        <RowDefinition Height="5"/>
        <RowDefinition Height="30"/>
        <RowDefinition Height="30"/>
    </Grid.RowDefinitions>

    <Rectangle Fill="{DynamicResource MutedWhite}" Grid.RowSpan="4" Grid.ColumnSpan="2"/>
    <TextBlock x:Name="textBlock" Grid.Column="1" Text="{Binding Path=Title}"  TextWrapping="Wrap" FontFamily="/Tasks;component/Assets/Fonts/#Abel" FontSize="24"/>
    <Rectangle Fill="{DynamicResource MutedGrey}" Grid.Row="1" Grid.ColumnSpan="2"/>

</Grid>

C# Code Behind:

public partial class Card : UserControl
{
    public Card()
    {
        InitializeComponent();
    }

    public string Title
    {
        get { return (string)GetValue(TitleProperty); }

        set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty TitleProperty =

      DependencyProperty.Register("Title", typeof(string), typeof(Card), new UIPropertyMetadata(""));

}

and on MainWindow.xaml

<Objects:Card Grid.Column="1" Grid.Row="1" Title="Say Something Here"/>

The rectangles are rendering but my text is not rendering in the control

I have tested this by adding text without the binding which works fine. However the problem is at the binding. I want to have the ability to set the text object on main window through the use of a xaml tag but I cannot do this as it will not show me. Any help appreciated :)

Upvotes: 0

Views: 183

Answers (1)

Clemens
Clemens

Reputation: 128060

The Text binding in the UserControl's XAML is missing a source object, which should be the UserControl instance.

One way to set the binding source to the UserControl instance is to set the RelativeSource property:

<TextBlock Text="{Binding Path=Title,
                  RelativeSource={RelativeSource AncestorType=UserControl}}" ... />

You may also set the x:Name attribute on the UserControl, and set the binding's ElementName:

<UserControl ... x:Name="self">
    ...
    <TextBlock Text="{Binding Path=Title, ElementName=self}" ... />
    ...
</UserControl>

Upvotes: 1

Related Questions