【问题标题】:Dynamically update style of control in UWP via a trigger通过触发器动态更新 UWP 中的控制样式
【发布时间】:2022-02-04 05:18:12
【问题描述】:

我想根据使用的类中的enum 在模板中显示控件的style。我尝试使用this to use the enum in XAMLthis to create a trigger。问题是我不能在 UWP 中使用 x:Static 并且触发器永远不会被触发。我的解决方法也不起作用。

我的班级:


//Namespace Enums
public enum ConnectionState
{
    Open,
    Closed,
    Connecting,
    Broken
}

//Namespace Models
public class DatabaseConnection : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private ConnectionState _connectionState = ConnectionState.Broken;
    public ConnectionState ConnState
    {
        get => _connectionState;
        set
        {
            if (value != _connectionState)
            {
                _connectionState = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(ConnStateInt));
                OnPropertyChanged(nameof(InfoBadgeStyle));
            }
        }
    }

    public int ConnStateInt => (int)ConnState;

    public Style InfoBadgeStyle
    {
        get
        {
            return ConnState switch
            {
                ConnectionState.Open => (Style)Application.Current.Resources["SuccessIconInfoBadgeStyle"],
                ConnectionState.Connecting => (Style)Application.Current.Resources["AttentionIconInfoBadgeStyle"],
                ConnectionState.Broken => (Style)Application.Current.Resources["CriticalIconInfoBadgeStyle"],
                _ => (Style)Application.Current.Resources["InformationalIconInfoBadgeStyle"],
            };
        }
    }
}

我的模板:

<Page.Resources>
    <DataTemplate x:Key="ConnectionTemplate" x:DataType="models:DatabaseConnection">
        <muxc:InfoBadge Style="{x:Bind InfoBadgeStyle}"/>
    </DataTemplate>
</Page.Resources>

如何在 UWP 中使用触发器更新样式?

【问题讨论】:

    标签: c# xaml uwp


    【解决方案1】:

    目前尚不清楚为什么您在 XAML 中同时具有 InfoBadgeStyle 属性和触发器,但如果您希望您的 ChangePropertyActions 能够设置 Style 属性,则不应将本地 Style 属性设置为它将优先:

    <muxc:InfoBadge ... Style="{x:Bind InfoBadgeStyle}">
    

    所以要么删除InfoBadgeStyle 属性,要么删除触发器。

    还要注意x:Bind 默认绑定OneTime,所以如果你想对更改通知做出反应,你应该将Mode 设置为OneWayStyle="{x:Bind InfoBadgeStyle, Mode=OneWay}"

    【讨论】:

    • 感谢您的回复。因为我实现了触发器,所以你的解决方案不起作用。它没有对属性更改做任何事情。
    • 什么不完全有效?
    • 当您更改属性的值时,不会引发 UI 事件。
    • 你在设置什么属性? InfoBadgeStyle?
    • 是的,我正在使用InfoBadgeStyle
    【解决方案2】:

    问题是该属性只绑定了一次。将Mode 设置为OneWay 解决了这个问题。感谢mm8 的提示。

    <muxc:InfoBadge Style="{x:Bind InfoBadgeStyle, Mode=OneWay}"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 2023-03-07
      相关资源
      最近更新 更多