[英]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.