Xamarin.forms 表单不调用转换器
我希望Xamarin.Forms应用程序中的Label元素占据高度的15%。所以,我是说我使用了转换器。以下是我使用的代码:Xamarin.forms 表单不调用转换器,xamarin.forms,binding,inotifypropertychanged,converters,ivalueconverter,Xamarin.forms,Binding,Inotifypropertychanged,Converters,Ivalueconverter,我希望Xamarin.Forms应用程序中的Label元素占据高度的15%。所以,我是说我使用了转换器。以下是我使用的代码: 我的.xaml文件 <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schem
我的.xaml文件
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converters="clr-namespace:ConverterClasses"
x:Class="App_for_e_Toilets.MainPage">
<ContentPage.Resources>
<ResourceDictionary>
<converters:DeviceProperties x:Key="DeviceProperties" />
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout>
<Label
BackgroundColor="Green"
HeightRequest="{Binding DeviceHeight, Converter={StaticResource DeviceProperties}}"
HorizontalOptions="FillAndExpand"
HorizontalTextAlignment="Center"
Text="Welcome"
TextColor="White"
FontAttributes="Bold"
VerticalTextAlignment="Center"/>
</StackLayout>
</ContentPage>
然而,当我运行应用程序时,似乎没有调用转换器(我从public object Convert
的断点在执行时没有破坏代码这一事实中意识到了这一点。我做错了什么
PS:这是我进入Xamarin.Forms的第二天,请记住我的代码你必须从实现
InotifyPropertyChanged
开始,并在ViewModel中使用backfield getter和setter创建绑定属性:
public MainPage()
{
BindingContext = new MainPageViewModel();
InitializeComponent();
}
1-创建一个助手类,该类将作为ViewModels的基础,并将实现激发InotifyPropertyChanged
事件的方法:
BaseViewModel.cs
public abstract class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = null)
{
if (!Equals(field, value))
OnPropertyChanged(name);
}
protected void OnPropertyChanged([CallerMemberName] string name = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public class MainPageViewModel : BaseViewModel
{
private double labelheight;
public double LabelHeight
{
get => labelheight;
set => SetProperty(ref labelheight, value);
}
}
LabelHeight
将存储标签的高度
由于您需要设备高度的百分比,因此可以将DeviceDisplay.main displayinfo.height
移动到转换器:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return 0.15 * DeviceDisplay.MainDisplayInfo.Height;
}
3-最后将BindingContext
设置为ViewModel:
public MainPage()
{
BindingContext = new MainPageViewModel();
InitializeComponent();
}
绑定与not变量一起工作,并且为了在ui和代码隐藏(逻辑)之间进行交互通信,当属性值发生更改时,需要实现Inotifypropertychanged
接口
相关链接:
您想让标签高度占总显示高度的50%?不,15%,但这个数字就在那里,因此我理解正在应用的高度,因为15%非常接近标签默认高度的15%。@Cfun否,设备高度:
public double DeviceHeight=DeviceDisplay.main displayinfo.height;
public MainPage()
{
BindingContext = new MainPageViewModel();
InitializeComponent();
}