简体   繁体   English

从公共类访问标签

[英]Accessing a label from a public class

I was curious as what the best practice would be to manipulate label properties from a class that is within the same name space and window as the labels.我很好奇从与标签位于相同名称空间和窗口的类中操作标签属性的最佳实践是什么。

Sample code:示例代码:

namespace SampleApplication1
{
    public partial class MainWindow : Window
    {
        public class labelController
        {
            public void setText()
            {
                //How do I reference label1 from here properly/in best practice to modify it's content?
            }
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        labelController lblCtrl = new labelController();

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            label1.Content = "Cows Go Moo!";
        }
    }
}

How would I reference the label, or any toolbox item from the setText function of labelController?我将如何从 labelController 的 setText 函数中引用标签或任何工具箱项目?

1.The best approach to manipulate label or any other UI Elements properties is to use databinding or MVVM pattern with WPF. 1. 操作标签或任何其他 UI 元素属性的最佳方法是将数据绑定或 MVVM 模式与 WPF 结合使用。

for example, you can databind your label properties to some member properties in code behind class(ie, Window class) as below:例如,您可以将标签属性数据绑定到类(即 Window 类)后面的代码中的某些成员属性,如下所示:

    <Label Content="{Binding LabelContent}" />

Where LabelContent is a member in your code behind class as below:其中 LabelContent 是您的类代码中的成员,如下所示:

 private string _LabelContent;
    public string LabelContent
    {
        get { return _LabelContent; }
        set
        {
            _LabelContent= value;
            RaisePropertyChangedEvent("LabelContent");
        }
    }

Or you can manipulate your label properties in a different class(view-model) other than your code-behind class and setting datacontext in your Window codebehind to point to the view-model class as below:或者,您可以在代码隐藏类之外的不同类(视图模型)中操作标签属性,并在窗口代码隐藏中设置数据上下文以指向视图模型类,如下所示:

 public class ViewModel : INotiFyPropertyChanged
{
    private string _LabelContent;
    public string LabelContent
    {
        get { return _LabelContent; }
        set
        {
            _LabelContent= value;
            RaisePropertyChangedEvent("LabelContent");
        }
        }
   }

 //setting datacontext is crucial in MVVM
 public partial class MainWindow : Window
{
    public ViewModel vm;

    public MainWindow ()
    {
        InitializeComponent();
        this.DataContext = new ViewModel();
 }

Remember in both cases, you need to implement INotifyPropertyChanged interface on both your Window class as well as your view-model class.请记住,在这两种情况下,您都需要在 Window 类和视图模型类上实现 INotifyPropertyChanged 接口。

the main purpose of INOtify... is to push data into the UI, whenever the data changes either in codebehind or in your viewmodel class or vice-versa(ie, changes in UI like some TextBox). INOtify 的主要目的是将数据推送到 UI 中,无论何时代码隐藏或视图模型类中的数据发生变化,反之亦然(即,UI 中的更改,如某些 TextBox)。 That way, you dont have to explicitly pull or push the data into UI from your codebehind/viewmodel.这样,您就不必从代码隐藏/视图模型中显式地将数据拉入或推送到 UI 中。

For example, your ButtonClick method could be changed as below:例如,您的 ButtonClick 方法可以更改如下:

 private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        LabelContent = "Cows Go Moo!";
    }

Since LabelContent is bound to Label Text property in your XAML file, the UI automatically changes the Label Text whenever ButtonClick method is executed.由于 LabelContent 绑定到 XAML 文件中的 Label Text 属性,因此只要执行 ButtonClick 方法,UI 就会自动更改标签文本。

PFB code for INOtify... interface: INOtify...接口的PFB代码:

    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChangedEvent(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            this.PropertyChanged(this, e);
        }
    }

You can find detailed info of MVVM, WPF Databinding as well as INotify.. interfaces in MSDN website.您可以在 MSDN 网站上找到有关 MVVM、WPF 数据绑定以及 INotify.. 接口的详细信息。

  1. If you want to change property of the label based on another property say, Content, then use a class that implements IConverter interface to dynamically change the property based on another property.如果您想根据另一个属性更改标签的属性,例如 Content,则使用实现 IConverter 接口的类来根据另一个属性动态更改该属性。 For example,例如,

     public class StringToColorConverter: IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string contentvalue=value.ToString(); var result = (contentvalue.Equals("something")) ? Brushes.Green : Brushes.Red; return result; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }

you can use the converter to change your background property based on content property in xaml as below:您可以使用转换器根据 xaml 中的内容属性更改背景属性,如下所示:

               <Window.Resources>
                <StringToColorConverter x:key="stringtocolorconverter"/>
                  </Window.Resources>

         <Label content="{Binding LabelContent}" Background="{Binding LabelContent, Converter={StaticResource stringtocolorconverter}}" />

or give label a name and convert background property by using label's content property as follows:或使用标签的内容属性为标签命名并转换背景属性,如下所示:

         <Label Name="LabelElement" content="{Binding LabelContent}" Background="{Binding Path=content, ElementName="LabelElement",Converter={StaticResource stringtocolorconverter}}" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM