How can I bind Foreground to a property in my ViewModel?

前端 未结 2 1211
-上瘾入骨i
-上瘾入骨i 2021-01-01 20:54

I would like to bind the foreground property of a TextBlock to a Property in my ViewModel.

This doesn\'t work :

Edit

View :

<
2条回答
  •  半阙折子戏
    2021-01-01 21:39

    This is not a good practice to put UI elements in your view model. Your view model must only encapsulate business locig.

    If you want to change the color of anything in your UI that depends on on the value of your textbox, it's a better practice to use data triggers in XAML.

    You can do like this :

    Viewmodel :

    public class MainVm : INotifyPropertyChanged
    {
        protected void OnPropertyChanged(string porpName)
        {
            var temp = PropertyChanged;
            if (temp != null)
                temp(this, new PropertyChangedEventArgs(porpName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    
        public string FullName
        {
            get { return "Hello world"; }
        }
    }
    

    XAML (Edited to use the color picker, assuming the selected value of his control is named "SelectedValue" and that it returns a Brush object)

        
        
        
    
    

提交回复
热议问题