我創建了一個具有 step 屬性的自定義視圖(NavProgressbar)。
private static readonly BindableProperty ProgressStepProperty = BindableProperty.Create(
nameof(ProgressStep), typeof(int), typeof(NavProgressbar),
0, BindingMode.TwoWay, propertyChanged: ProgressStepPropertyChanged);
private static void ProgressStepPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
//update view, removed for brevity
}
public int ProgressStep
{
get => (int)GetValue(ProgressStepProperty);
set => SetValue(ProgressStepProperty, value);
}
在我的 MvxContentPage 中,我可以通過設定 ProgressStep 的值來使用它
<npb:NavProgressbar
x:Name="NavProgressBar"
ProgressStep="2"/>
到目前為止有效。現在我想從我的視圖模型中設定它,所以在我的視圖模型中我創建了一個屬性......
private int _progressStep;
public int ProgressStep
{
get => _progressStep;
set => SetProperty(ref _progressStep, value);
}
...并且在我的 MvxContentPage 而不是固定值中,我通過執行系結到我的 viewmodel 屬性
<npb:NavProgressbar
x:Name="NavProgressBar"
ProgressStep="{Binding ProgressStep}"/>
但它不起作用。按鈕和標簽等的其他系結作業正常。我的錯誤在哪里?
編輯:在我的 MvxContentPage 中,我設定了 NavProgressbar
xmlns:viewModels="clr-namespace:x.y.z.ViewModels;assembly=myAssembly"
x:TypeArguments="viewModels:myViewModel"
x:DataType="viewModels:myViewModel"
和 Resharper 在系結中顯示
ProgressStep="{Binding path={myViewModel}.ProgressStep}"
所以我認為系結背景關系設定正確。也許視圖和視圖模型是抽象的也很重要,我正在使用這個抽象視圖和視圖模型的子類?
其他系結按預期作業,例如 Resharper 顯示的按鈕
<Button
Text="{Binding path={myViewModel}.ButtonText}"
uj5u.com熱心網友回復:
您需要將 BindingContext 設定為指向 ViewModel。
用于{Binding _____}連接 C# 屬性時,XAML 需要知道它系結到什么。默認情況下,它將系結到與其關聯的代碼隱藏檔案。以下可能對您有用(仔細檢查命名空間是否正確):
<npb:NavProgressbar
x:Name="NavProgressBar"
ProgressStep="{Binding ProgressStep}"
<npb:NavProgressbar.BindingContext>
<npb:NavProgressBarViewModel />
</npb:NavProgressbar.BindingContext>
/>
微軟的這個頁面有一些關于 BindingContext 如何作業的很好的例子: https ://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm
uj5u.com熱心網友回復:
根據您提供的代碼,一切正常。因此,如果您確保該屬性將呼叫視圖模型中的屬性更改事件,您可以檢查類似的案例,該案例有一個示例顯示如何將自定義視圖中的可系結屬性系結到視圖模型。
案例鏈接:獲取控制元件中 ViewModel 中使用的 BindableProperty 的值?
uj5u.com熱心網友回復:
所以,問題是 Resharper 建議將此屬性設為私有
private static readonly BindableProperty ProgressStepProperty =
BindableProperty.Create(nameof(ProgressStep), typeof(int), typeof(NavProgressbar), 0, BindingMode.TwoWay, propertyChanged: ProgressStepPropertyChanged);
我做了,但它必須是公開的
public static readonly BindableProperty ProgressStepProperty =
BindableProperty.Create(nameof(ProgressStep), typeof(int), typeof(NavProgressbar), 0, BindingMode.TwoWay, propertyChanged: ProgressStepPropertyChanged);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/478214.html
標籤:xml xamarin.forms 数据绑定 视图模型
