【发布时间】:2021-05-24 08:00:00
【问题描述】:
我正在寻找一种通过单选按钮控制标签文本的方法。我已经阅读了本网站以及其他网站上的类似问题,但无法找到可行的解决方案。我尝试使用转换器以及将单选按钮放入列表中。当我通过调试器运行代码时,视图模型中的单选按钮代码永远不会到达。任何帮助,将不胜感激。 这是我的视图的代码:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="sampleRadioButtons.Views.ButtonPage"
xmlns:vm="clr-namespace:sampleRadioButtons.ViewModels">
<ContentPage.BindingContext>
<vm:MainPageViewModel/>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout VerticalOptions="Center">
<StackLayout Orientation="Horizontal" RadioButtonGroup.GroupName="time">
<RadioButton Content="One Year" IsChecked="{Binding YearChecked, Mode=TwoWay}"/>
<RadioButton Content="One Month" IsChecked="{Binding MonthChecked, Mode=TwoWay}"/>
<RadioButton Content="One Week" IsChecked="{Binding WeekChecked, Mode=TwoWay}"/>
</StackLayout>
<Label Text="Total is"/>
<Label Text="{Binding Total}"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
这是我对应的视图模型:
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace sampleRadioButtons.ViewModels
{
public class MainPageViewModel : INotifyPropertyChanged
{
public MainPageViewModel()
{
total = GetTotal();
}
public void OnPropertyChange([CallerMemberName] string name = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private string total;
public string Total
{
get { return total; }
set
{
total = value;
OnPropertyChanged();
}
}
private bool yearChecked;
public bool YearChecked
{
get { return yearChecked; }
set
{
yearChecked = value;
OnPropertyChange();
}
}
private bool monthChecked;
public bool MonthChecked
{
get { return monthChecked; }
set
{
monthChecked = value;
OnPropertyChange();
}
}
private bool weekChecked;
public bool WeekChecked
{
get { return weekChecked; }
set
{
weekChecked = value;
OnPropertyChange();
}
}
public string GetTotal()
{
if(YearChecked == true) { return "$10"; }
if(monthChecked == true) { return "$20"; }
if(weekChecked == true) { return "30"; }
else { return "$50"; }
}
}
}
【问题讨论】:
-
是错字吗? WeekClicked(在 xaml 绑定中)- WeekChecked(在 vm 代码中)?
-
是的,这不会改变任何事情。我尝试制作一个示例应用程序,因此我不必发布我正在开发的实际应用程序
-
您能修改并更正您发布的代码吗?这可能会让愿意帮助你的人感到困惑
-
我现在更正了,感谢您指出这一点
标签: xaml xamarin.forms mvvm data-binding radio-button