我有 3 DependencyProperty 的自定义控件:
<UserControl x:Class="WpfDemoApp.NewsCard" [...]>
<Border BorderThickness="10" CornerRadius="10" BorderBrush="Wheat" Background="Wheat" Margin="3">
<StackPanel Background="Wheat">
<TextBlock Text="{Binding Date}" TextAlignment="Left"/>
<TextBlock Text="{Binding Title}" FontWeight="Bold" TextAlignment="Left" TextWrapping="Wrap" Margin="0, 3, 0, 3"/>
<TextBlock Text="Description:" FontWeight="Bold" />
<TextBlock Text="{Binding Text}" TextAlignment="Justify" TextWrapping="Wrap" TextTrimming="WordEllipsis"/>
</StackPanel>
</Border>
</UserControl>
在 C# 代码中:
public partial class NewsCard : UserControl
{
public NewsCard()
{
InitializeComponent();
DataContext = this;
}
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string), typeof(NewsCard), new UIPropertyMetadata("<title>"));
public string Date
{
get { return (string)GetValue(DateProperty); }
set { SetValue(DateProperty, value); }
}
public static readonly DependencyProperty DateProperty =
DependencyProperty.Register("Date", typeof(string), typeof(NewsCard), new UIPropertyMetadata("01.01.1970"));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(NewsCard), new UIPropertyMetadata("<text>"));
}
我正在使用以下 XML 数据提供程序:
<XmlDataProvider x:Key="RssData" XPath="//item" Source="http://www.engadget.com/rss.xml"/>
并尝试在主窗口 XAML 文件中使用它:
<demo:NewsCard Title="{Binding Source=RssData, XPath=title[1]}" Date="{Binding Source=RssData, XPath=pubDate[1]}" Text="{Binding Source=RssData, XPath=description[1]}"/>
所有属性都收到相同的错误消息:
System.Windows.Data Error: 45 : BindingExpression with XPath cannot bind to non-XML object.; XPath='title[1]' BindingExpression:Path=/InnerText; DataItem='String' (HashCode=-696447263); target element is 'NewsCard' (Name=''); target property is 'Title' (type 'String') RssData
当我在 TextBox 控件的 Text 属性中使用完全相同的绑定表达式时,一切正常。当我尝试将它与我的控件一起使用时出了什么问题?非常感谢帮助!