【问题标题】:How to bind the BackgroundColor property of a view to a View Model in Xamarin Forms?如何将视图的 BackgroundColor 属性绑定到 Xamarin Forms 中的视图模型?
【发布时间】:2020-06-08 00:30:50
【问题描述】:

因此,我正在使用 Fresh MVVM 在 Xamarin Forms 中制作应用程序,并且我希望在按下按钮时执行事件,并且仅当按钮的 BackgroundColor 为白色时。 按钮的 backgroundColor 会在 XAML.CS 中改变,而这个事件会在 ViewModel 中发生。

问题在于,在我拥有 ViewModel 属性的当前代码中,所有原色和属性都设置为 0,而不是实际的按钮颜色属性。我已经在寻找答案,但没有任何帮助。

XAML 代码如下:

<Button
            x:Name="Button_NextStep"
            HeightRequest="50"
            WidthRequest="400"
            BackgroundColor="{Binding NextStepBackgroundColor}"
            CornerRadius="30"

            Text="Next step"
            TextColor="#4847FF"
            FontAttributes="Bold"
            FontSize="20"

            VerticalOptions="Start"
            HorizontalOptions="Start"
            Margin="25,178,25,5"

            Command="{Binding NextStep}"
></Button>

ViewModel 代码:

class CreateAccount_UsernameViewModel: FreshBasePageModel
    {
        public ICommand NextStep { get; set; }
        public Color NextStepBackgroundColor { get; set; }

        public InavigationService navigationService; //this is irrelevant for this question

        public CreateAccount_UsernameViewModel(InavigationService _navService)
        {
            navigationService = _navService; //this is irrelevant for this question

            NextStep = new Command(() =>
            {
                if (NextStepBackgroundColor == Color.FromHex("#FFD3D3D3"))
                    navigationService.SwitchNavigationStacks(Enums.NavigationStacks.CreateAccount, this); //this is irrelevant for this question
            });
        }
    }

仅此而已,如果您需要更多信息来促进解决方案,我会在看到您的请求后立即提供给您。谢谢大家的时间,希望你有一个美好的一天。

【问题讨论】:

  • Binding Mode 设置为OneWayToSource。请检查它是否解决了您的问题
  • @Nikhileshwar 成功了,非常感谢。如果问的不多,您能向我解释一下“OneWayToSource”在这种情况下有什么不同吗?
  • 肯定会添加为答案。
  • 我已经添加了解释anwser请检查

标签: c# xaml xamarin mvvm xamarin.forms


【解决方案1】:

主要的绑定模式是 - (Expect OneTime and Default(self-explanatory from name))

  1. OneWay = ViewModel 中的值更改设置为 View(此处按钮)。这是大多数属性的默认设置。

  2. TwoWay = ViewModel 和 View 中的值更改得到通知。这设置为从源端更改的属性,例如EntryText 属性、ListViewSelectedItem 属性等等。

  3. OneWayToSource = View 中的值更改会通知给 ViewModel,但 ViewModel 中的值更改不会通知给 View。

您的方案中的问题是ButtonBackgroundColorBindingMode 属性默认为OneWay,将BackgroundColorButtonBindingMode 保留为TwoWay 因为控制端的值不会改变。

但是BackgroundColor属性的变化必须反映在ViewModel中,因此BindingMode必须设置为OneWayToSource

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2020-01-29
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多