为了账号安全,请及时绑定邮箱和手机立即绑定

如何将列表视图项目绑定到页面的 Viewmodel?

如何将列表视图项目绑定到页面的 Viewmodel?

C#
LEATH 2023-05-13 15:51:15
我想将项目绑定ListView到 ViewModel 中的属性而不是 ItemsSource,但在尝试后Binding Source={x:Reference Name=ThisPage} Path=ViewModel.TimerValue它不起作用。我做错了什么。无法识别我试过设置:Text="{Binding Path=TimerValue, TargetNullValue='00:00', FallbackValue='00:00', StringFormat='{0:mm\\:ss}', Source={x:Reference Name=ThisPage}}"ViewModel 确实实现了 INotifyPropertyChanged 并引发了 PropertyChanged 事件页面标题 - 参考<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"             xmlns:d="http://xamarin.com/schemas/2014/forms/design"             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"             mc:Ignorable="d"             x:Class="App3.Views.MyPage"             x:Name="ThisPage"><ListView x:Name="listView" ItemsSource={Binding Items}>                <ListView.ItemTemplate>                    <DataTemplate>                        <ViewCell>                            <Label Text="{Binding Path=TimerValue, TargetNullValue='00:00', FallbackValue='00:00', StringFormat='{0:mm\\:ss}', Source={x:Reference Name=ThisPage}}" />                        </ViewCell>                    </DataTemplate>                </ListView.ItemTemplate>            </ListView>代码隐藏 private MyViewModel ViewModel; public MyPage () {     InitializeComponent ();     ViewModel = new MyViewModel ();     this.BindingContext = ViewModel; }
查看完整描述

3 回答

?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

我解决了它如下


<Label Text="{Binding TimerValue, TargetNullValue='00:00', FallbackValue='00:00', StringFormat='{0:mm\\:ss}'}"

        BindingContext="{Binding Source={x:Reference MyPage}, Path=BindingContext}">

绑定错误的原因,BindingContext必须是BindableObject。 BindingContext是可绑定对象,它又引用ViewModel对象,并且Label.Text必须是BindableProperty可绑定对象。当我引用它时Text={Binding ViewModel.TimerValue,它试图在中找到可绑定属性,Mypage但是ViewModel它只是一个公共属性,而不是 Bindable 对象BindingContext = ViewModel将其转换为 Bindable 对象,因此我不得不对 Source 使用这种方式,而 Text 只是调用该引用的 bindingcontext 的路径


感谢所有的建议!非常感谢这个社区的及时响应!


查看完整回答
反对 回复 2023-05-13
?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

迟到的答案,但可能会对某人有所帮助。如果您在后面的代码中编写布局。您可以以这种方式将上下文绑定到源视图模型上下文。我将一个按钮绑定到视图模型中的命令。


btn.SetBinding(Button.CommandProperty, new Binding("BindingContext.YourCommand", source: YourListView));

btn.SetBinding(Button.CommandParameterProperty, ".");


查看完整回答
反对 回复 2023-05-13
?
炎炎设计

TA贡献1808条经验 获得超4个赞

两步..

  1. 为您的父视图提供一个引用名称x:Name="viewName"(绑定到 ViewModel 的视图)

  2. 绑定如下: "{Binding BindingContext.MenuTapCommand, Source={x:Reference viewName}}"

这行得通。


查看完整回答
反对 回复 2023-05-13
  • 3 回答
  • 0 关注
  • 112 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信