我不知道我的代码出了什么问题。我创建了自己的控制元素ControlA
的示例(在代码中创建)。它有一个Data
属性,包含一些结构。它显示部分数据,我想使用另一个自定义控件ControlB
来显示数据的子集。但是,当我使用xaml中A组件的数据设置ControlB
组件的属性时,它不会出现。
怎么了?
创建ControlA
:
var controlA = new ControlA();
controlA.Data = new Tuple<string, string>("Some text data", "Some subset data");
_grid.Children.Add(controlA);
ControlA
:
<?xml version="1.0" encoding="utf-8"?>
<UserControl
x:Class="winui_3_app.components.ControlA"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:winui_3_app.components"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<StackPanel>
<Grid Background="Aquamarine">
<TextBlock Text="{Binding Data.Item1}" />
</Grid>
<Grid Background="Coral">
<local:ControlB Text="{Binding Data.Item2}" />
</Grid>
</StackPanel>
</UserControl>
using System;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
namespace winui_3_app.components;
public sealed partial class ControlA : UserControl
{
public Tuple<string, string> Data
{
get => (Tuple<string, string>)GetValue(DataProperty);
set => SetValue(DataProperty, value);
}
public static readonly DependencyProperty DataProperty = DependencyProperty.Register(nameof(Data), typeof(Tuple<string, string>), typeof(ControlA), new PropertyMetadata(null));
public ControlA()
{
this.InitializeComponent();
this.DataContext = this;
}
}
ControlB
:
<?xml version="1.0" encoding="utf-8"?>
<UserControl
x:Class="winui_3_app.components.ControlB"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:winui_3_app.components"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
<TextBlock Text="{Binding Text}" />
</Grid>
</UserControl>
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
namespace winui_3_app.components;
public sealed partial class ControlB : UserControl
{
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(ControlB), new PropertyMetadata(string.Empty));
public ControlB()
{
this.InitializeComponent();
this.DataContext = this;
}
}
1条答案
按热度按时间wztqucjr1#
因此,由于某种原因,绑定无法解析(也许有人可以添加原因),并且您得到
Error: BindingExpression path error: 'Data' property not found on 'CustomInCustom.ControlB'. BindingExpression: Path='Data.Item2' DataItem='CustomInCustom.ControlB'; target element is 'CustomInCustom.ControlB' (Name='null'); target property is 'Text' (type 'String')
即使ControlA
的DataContext
已经设置。也许是因为ControlB
在ControlA
之前加载?我不确定。重要的是,解决方案是将
Binding
替换为x:Bind
。