XAML BoxView和RGBA值未显示

3hvapo4f  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(91)
//model
public class ColorModel
{
    private Color _colorCard;

    public Color ColorCard
    {
        get { return _colorCard; }
        set { _colorCard = value; }
    }
    public int R
    {           
        get { return (int)(_colorCard.R * 255); }
        set { _colorCard = Color.FromRgba(  value,  _colorCard.G, _colorCard.B, _colorCard.A); }
    }

    //viewmodel:INotifyPropertyChanged
    private ObservableCollection<ColorModel> colorList;
       
       private ColorModel _colorModel;  

        public Color ColorCardView
        {
            get { return _colorModel.ColorCard; }
            set
            {
                if (_colorModel.ColorCard != value)
                {
                    _colorModel.ColorCard = value;
                    NotifyPropertyChanged();
               }
            }
        }

       public int RView
        {
            get { return _colorModel.R; }
            set
            {
                if (_colorModel.R != value)
                {
                    _colorModel.R = value;
                    NotifyPropertyChanged();
                }
            }
        }

这是我的XAML代码:

<BoxView Color="{Binding ColorCardView}" WidthRequest="100"HeightRequest="50"/>                                            
<Label FontSize ="Medium" Text="{Binding RView}"

代码成功运行,但BoxView没有显示绑定到它的color属性,R(fromrgba)值也没有显示。

ojsjcaue

ojsjcaue1#

您需要创建一个_colorModel的新示例,然后在视图模型构造函数中设置它。您可以参考下面的示例代码:

public class MainPageViewModel : INotifyPropertyChanged 
{

        private ColorModel _colorModel { get; set; }

        public MainPageViewModel()
        {
            _colorModel = new ColorModel()
            {
                ColorCard = Colors.Red,
                R = 255
            };
        }

        public Color ColorCardView
        {
            get { return _colorModel.ColorCard; }
            set
            {
                if (_colorModel.ColorCard != value)
                {
                    _colorModel.ColorCard = value;
                    OnPropertyChanged();
                }
            }
        }

        public int RView
        {
            get { return _colorModel.R; }
            set
            {
                if (_colorModel.R != value)
                {
                    _colorModel.R = value;
                    OnPropertyChanged();
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propName = null)
        {
            PropertyChanged?.Invoke(this,
                 new PropertyChangedEventArgs(propName));
        }
}

最后,不要忘记像下面这样设置视图的BindingContext

BindingContext = new MainPageViewModel();

相关问题