代码之家  ›  专栏  ›  技术社区  ›  user8162574

WPF自定义控件不显示数据

  •  0
  • user8162574  · 技术社区  · 7 年前

    这里有我的自定义控件:

    <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标记在主窗口上设置文本对象,但我无法做到这一点,因为它不会显示给我。非常感谢您的帮助:)

    1 回复  |  直到 7 年前
        1
  •  1
  •   Clemens    7 年前

    UserControl的XAML中的文本绑定缺少一个源对象,该对象应该是UserControl实例。

    将绑定源设置为UserControl实例的一种方法是设置 RelativeSource 属性:

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

    x:Name 属性,并设置绑定的 ElementName

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