在这里我有我的自定义控件:
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#代码背后:
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(""));
}
和mainwindow.xaml
<Objects:Card Grid.Column="1" Grid.Row="1" Title="Say Something Here"/>
矩形正在渲染,但我的文字在控件中没有呈现
我已经通过添加文本而无需绑定来测试了这一点。但是,问题是在绑定中。我想通过使用XAML标签在主窗口上设置文本对象的能力,但是我不能这样做,因为它不会向我展示。任何帮助:(
userControl XAML中绑定的文本缺少一个源对象,该对象应该是usercontrol实例。
将绑定源设置为userControl实例的一种方法是设置RelativeSource
属性:
<TextBlock Text="{Binding Path=Title,
RelativeSource={RelativeSource AncestorType=UserControl}}" ... />
您还可以在UserControl上设置x:Name
属性,并设置绑定的ElementName
:
<UserControl ... x:Name="self">
...
<TextBlock Text="{Binding Path=Title, ElementName=self}" ... />
...
</UserControl>