![](/img/trans.png)
[英]MVVM Xamarin Forms - Command Pararameter to Bind View Model property
[英]How to bind the BackgroundColor property of a view to a View Model in Xamarin Forms?
所以我正在 Xamarin Forms 中制作一个应用程序,使用 Fresh MVVM,我希望在按下按钮时执行一个事件,并且仅当按钮的 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>
视图模型代码:
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
});
}
}
这就是全部,如果您需要更多信息来促进解决方案,我会在看到您的请求后立即提供给您。 谢谢大家的时间,希望你有一个美好的一天。
主要的绑定模式是 -( Expect OneTime 和 Default(名称不言自明))
OneWay
= ViewModel 中的值更改设置为 View(此处为按钮)。 这是大多数属性的默认设置。
TwoWay
= ViewModel 和 View 中的值更改都得到通知。 这被设置为从源端更改的属性,例如Entry
的Text
属性、 ListView
SelectedItem
属性等。
OneWayToSource
= View 中的值更改会通知 ViewModel,但 ViewModel 中的值更改不会通知 View。
在方案中的问题是, BindingMode
的BackgroundColor
的属性Button
是OneWay
默认情况下,它也没有任何意义,以保持BindingMode
的BackgroundColor
的Button
为TwoWay
的价值不是从控制端去改变。
但在变化BackgroundColor
属性在视图模型中得到体现,因此BindingMode必须被设置为OneWayToSource
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.