[英]How do a make a TextBlock control that can be disabled in WinUI3?
我试图在禁用父控件时使自定义UserControl
中的一些TextBlock
控件变灰(即IsEnabled = false
)。 对于标准控件的标题等,这会自动发生,但是TextBlock
控件保持黑色。 我认为这是因为他们没有IsEnabled
属性。
我尝试像这样制作另一个UserControl
:
<UserControl
x:Class="MyApp.DisableableTextBlock"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
IsEnabledChanged="UserControl_IsEnabledChanged">
<UserControl.Resources>
<SolidColorBrush x:Key="EnabledColour" Color="{StaticResource TextFillColorPrimary}"/>
<SolidColorBrush x:Key="DisabledColour" Color="{StaticResource TextFillColorDisabled}"/>
</UserControl.Resources>
<TextBlock x:Name="TextBlock" Text="{x:Bind Text, Mode=OneWay}"/>
</UserControl>
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
namespace MyApp
{
public sealed partial class DisableableTextBlock : UserControl
{
public DisableableTextBlock()
{
InitializeComponent();
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register(nameof(Text), typeof(string), typeof(DisableableTextBlock), new PropertyMetadata(""));
private void UserControl_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
TextBlock.Foreground = Resources[IsEnabled ? "EnabledColour" : "DisabledColour"] as SolidColorBrush;
}
}
}
其目的是在控件被禁用时更改文本的颜色。 但是,启用或禁用父控件时不会触发IsEnabledChanged
事件。 这似乎与文档不符。
我错过了什么? 当禁用父级时,是否有更好的方法来“禁用” TextBlock
控件?
IsEnabledChanged
将在您更改时触发。 您正在设置默认值,但您没有更改它。
所以,你需要添加这样的东西。
private void DisableableTextBlock_Loaded(object sender, RoutedEventArgs e)
{
TextBlock.Foreground = Resources[IsEnabled ? "EnabledColour" : "DisabledColour"] as SolidColorBrush;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.