简体   繁体   中英

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?

1.The best approach to manipulate label or any other UI Elements properties is to use databinding or MVVM pattern with WPF.

for example, you can databind your label properties to some member properties in code behind class(ie, Window class) as below:

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

Where LabelContent is a member in your code behind class as below:

 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.

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). That way, you dont have to explicitly pull or push the data into UI from your codebehind/viewmodel.

For example, your ButtonClick method could be changed as below:

 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.

PFB code for INOtify... interface:

    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.

  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. 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:

               <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}}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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