我创建了一个自定义控件,该控件应该用作项目视图中的按钮,但是,更改其文本的绑定不起作用。
CustomControls(Winui3类库项目)/CustomTableItem.cs
namespace CustomControls
{
public sealed class CustomTableItem : Control
{
DependencyProperty TableNameProperty = DependencyProperty.Register(
nameof(TableName),
typeof(string),
typeof(CustomTableItem),
new PropertyMetadata(null));
public string TableName
{
get => (string)GetValue(TableNameProperty);
set => SetValue(TableNameProperty, value);
}
public CustomTableItem()
{
this.DefaultStyleKey = typeof(CustomTableItem);
}
public CustomTableItem(string TableName)
{
this.DefaultStyleKey = typeof(CustomTableItem);
this.TableName = TableName;
}
}
}
自定义控件/主题/Generic.xaml
//one other style above [...]
<Style TargetType="local:CustomTableItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomTableItem">
<Grid Height="150" Width="150" Background="White">
<TextBlock Text="..." Height="15" Width="20" HorizontalAlignment="Right" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"
TextWrapping="Wrap"
Text="{Binding TableName, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay, FallbackValue='Error Binding'}"
Style="{StaticResource BodyStrongTextBlockStyle}"
FontSize="20"
>
</TextBlock>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
View(打包的winui3项目)/CustomTablePage.xaml
<Page
x:Class="View.CustomTablePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:View"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:customControls ="using:CustomControls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<customControls:CustomTableItem TableName="This doesnt show in the label"/>
使用
ContentFrame.Navigate()
函数显示 CustomTablePage
最终结果:
当我将完全相同的控件放置在实例化一次并重用的页面中时(
ContentFrame.Content = PageObject
)该属性有效:
其他页面位置:View/PageName.xaml。 代码:
<CustomControls:CustomTableItem TableName="Custom table name"></CustomControls:CustomTableItem>
我尝试更改模板文本属性中的绑定,但仍然不起作用。我看到一些答案谈论名为 DataContex 的东西,但我不明白它是如何工作的,而且我注意到它们中的大多数都使用用户控件而不是自定义控件或 WPF。