亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將列表視圖項目綁定到頁面的 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 關注
  • 192 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號