[英]How can I programmatically access a specific Run after adding it to a Windows.UI.Xaml.Controls.TextBlock?
[英]How to access textblock or UI Element in static class and set the properties
如何从另一个静态类或静态类助手访问 XAML 页面中的文本块或文本框或矩形框或 UI 元素以执行任务。
我有这个问题:
XAML 页面中的 textBlock:
1) 如何在静态类中访问此文本块以通过静态类设置文本块的前景色或设置背景矩形框或其他 UI 元素:
2) 如何将 textBlock 传递给静态类并将其设置如下
textBlock.Foreground = Brushes.Navy;
谢谢
虽然你问的一般来说真的不是一个好主意,但它可以做到(但同样有更好的方法)。
所以基本上你可以将 Dispatcher 和 TextBox 分配给页面 OnNavigatedTo 方法中静态类中的某些字段或属性。
您需要分配两者,因为您只能从 UI 线程访问 TextBox,并且可以通过 Dispatcher.RunAsync 方法调用它。
编辑:
<TextBox Name="textBox"/>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
myStaticClass.TextBox = textBox;
myStaticClass.Dispatcher = Dispatcher;
}
您可以使用绑定:
Xml:
<TextBlock x:Name="AppStatusValueTextBlock" HorizontalAlignment="Left" Margin="1035,174,0,0" TextWrapping="Wrap" Text="{Binding ChangeTextBlockText}" VerticalAlignment="Top" Height="30" Width="230"/>
C#-类:
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));
}
}
编辑:更改前景色的示例
Xml:
<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));
}
}
主页.cs:
public MainPage()
{
this.InitializeComponent();
ViewModel daViewModel = new ViewModel();
DataContext = daViewModel;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.