c# - 如何将 XAML contentView 绑定到其背后的代码
问题描述
我有一些 UI 逻辑,我需要在后面的代码中添加它们。为了克服代码重复,我需要使用一个属性并对其进行更改。正常的 MVVM 事情。但是当我尝试用 Codebehind 来做这件事时。意味着我将 XAML 与我的代码绑定,以便在多个位置访问 isvisible 函数。问题是它没有绑定或任何其他问题的可见性在触发操作时没有改变。
我的 ContentView Xaml
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:customRenderes="clr-namespace:DipsDemoXaml.CustomRenderes;assembly=DipsDemoXaml"
x:Class="DipsDemoXaml.Views.Page1"
x:Name="navi">
<StackLayout BindingContext="{x:Reference Name=navi}">
<customRenderes:NavigationImageButton Source="MenuSettings"
x:Name="Button1"
Margin="0"
IsVisible="{Binding Visibility}"
/>
在后面的代码中
public partial class Page1 : ContentView
{
private bool _expand;
private bool _visibility;
public bool Visibility
{
get => _visibility;
set
{
_visibility = value;
OnPropertyChanged();
}
}
public Page1 ()
{
InitializeComponent ();
}
private void Button1_OnItemTapped(object sender, EventArgs e)
{
if (_expand)
{
this.Hide();
}
else
{
this.Expand();
}
}
private async void Expand()
{
_expand = true;
Button5.Opacity = 1;
_visibility = true;
await Button5.RotateTo(180, 200);
}
private async void Hide()
{
_expand = false;
Button5.Opacity = 0.4;
_visibility = false;
await Button5.RotateTo(360, 200);
}
}
如何以 xamarin 形式绑定它。我的绑定是错误的还是问题出在哪里
我的 onpropertychanged 方法
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
changed?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
解决方案
首先,PropetyChanged 接受一个参数,
OnPropertyChanged("Visibility");
我想这应该可以,但是将您的 ViewModel 代码放在后面的代码中很奇怪。
MVVM 的想法是将逻辑从页面移动到 ViewModel,允许您在 XAML 后面的页面中使用几乎(如果不是)0 代码来管理同一 ViewModel 中多个页面的状态。
因此,您可能应该创建另一个名为 ViewModel 的文件,并将您的业务逻辑放入其中。
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:customRenderes="clr-
namespace:DipsDemoXaml.CustomRenderes;assembly=DipsDemoXaml"
x:Class="DipsDemoXaml.Views.Page1"
xmlns:vm="clr-namespace:DipsDemoXaml.ViewModels;assembly=DipsDemoXaml"
x:Class="DipsDemoXaml.Views.Page1"
x:Name="navi">
<ContentView.BindingContext>
<vm:MyViewModel/>
</ContentView.BindingContext>
<StackLayout>
<customRenderes:NavigationImageButton Source="MenuSettings"
x:Name="Button1"
Margin="0"
IsVisible="{Binding Visibility}"/>
在 MyViewModel.cs 中:
private bool _visibility;
public bool Visibility
{
get => _visibility;
set
{
_visibility = value;
OnPropertyChanged("Visibility");
}
}
因此,您可以处理您想要的任何绑定,并在不同的页面中轻松使用它们。
我希望这有帮助。
推荐阅读
- python - 中断命令不会停止循环
- sql-server-2016 - Coldfusion cfqueryparam - 改变编码?
- python - 强制 requests.get 在 python 中使用没有百分比编码的方括号
- javascript - 如何向下滚动到隐藏部分
- python - 使用 gzip.open() 编写的 Python 3 无法将压缩文件上传到云存储
- javascript - 如何从这些对象中获取值
- php - 方法 Illuminate\\Auth\\RequestGuard::attempt 不存在
- php - 从 PHP 读取 Windows 安装程序(MSI 文件)属性
- github - 你如何限制贡献者在没有 Fork 的情况下推送到私有存储库?
- javascript - React元素中的鼠标滚轮/滚动事件没有溢出(图片缩放)