[英]WPF Custom Control Not Displaying Data
這是我的自定義控件:
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中的Text綁定缺少源對象,該對象應該是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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.