如何访问静态 class 中的文本块或 UI 元素并设置属性

How to access textblock or UI Element in static class and set the properties

如何从另一个静态 class 或静态 class 助手访问 XAML 页面中的文本块或文本框或矩形框或 UI 元素来执行任务.

我有这个问题:
XAML 页面中的文本块:

1) 如何在静态 class 中访问此文本块以设置文本块的前景色或设置背景矩形框或其他 UI 元素通过静态 Class:

2) 如何将 textBlock 传递给静态 class 并将其设置如下

textBlock.Foreground = Brushes.Navy;

谢谢

虽然你问的不是一个好主意,但总的来说它是可以做到的(但同样有更好的方法)。

所以基本上您可以将 Dispatcher 和 TextBox 分配给页面 OnNavigatedTo 方法中静态 class 中的某个字段或 属性。

您需要分配两者,因为您只能从 UI 线程访问 TextBox,并且您可以通过 Dispatcher.RunAsync 方法调用它。

编辑:

<TextBox Name="textBox"/>

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    myStaticClass.TextBox = textBox;
    myStaticClass.Dispatcher = Dispatcher;
}

您可以使用绑定:

Xaml:

<TextBlock x:Name="AppStatusValueTextBlock" HorizontalAlignment="Left" Margin="1035,174,0,0" TextWrapping="Wrap" Text="{Binding ChangeTextBlockText}" VerticalAlignment="Top" Height="30" Width="230"/>

C#-Class:

class YourClass : INotifyPropertyChanged
{

 private string _changeTextBlockText;

 public string ChangeTextBlockText{
                get
                {
                    return _changeTextBlockText;
                }
                set
                {
                    _changeTextBlockText= value;
                    OnPropertyChanged();
                }
        }


 public event PropertyChangedEventHandler PropertyChanged;

 protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
 {
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
 }

}

编辑:更改前景色的示例

Xaml:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBlock x:Name="textBlockHex" HorizontalAlignment="Left" Margin="90,180,0,0" TextWrapping="Wrap" Text="hello" VerticalAlignment="Top" Height="75" Width="170" Foreground="{Binding TextBlockColorInHex}"/>
</Grid>

视图模型:

class ViewModel : INotifyPropertyChanged
{

    public string TextBlockColorInHex
    {
        get
        {
            return _textBlockColorInHex;
        }
        set
        {
            this._textBlockColorInHex = value;
            this.OnPropertyChanged();
        }
    }

    public ViewModel()
    {
       SetColorFromThisClass("#ff0000");
    }

    private void SetColorFromThisClass(string colorInHex)
    {
        TextBlockColorInHex = colorInHex;
    }
    private string _textBlockColorInHex;


    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

MainPage.cs:

    public MainPage()
    {
        this.InitializeComponent();

        ViewModel daViewModel = new ViewModel();
        DataContext = daViewModel;

    }