XAML 将ViewModel属性绑定到自定义视图中的属性

cnjp1d6j  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(150)

我创建了一个自定义视图(NavProgressbar),它有一个step属性。

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}"

nr7wwzry

nr7wwzry1#

您需要设置BindingContext以指向ViewModel。
当使用{Binding _____}连接C#属性时,XAML需要知道它绑定到什么。默认情况下,它将绑定到与之关联的文件背后的代码。以下可能适用于您(仔细检查命名空间是否正确):

<npb:NavProgressbar
            x:Name="NavProgressBar"
            ProgressStep="{Binding ProgressStep}"
            <npb:NavProgressbar.BindingContext>
                <npb:NavProgressBarViewModel />
            </npb:NavProgressbar.BindingContext>
    />

字符串
微软的这个页面有一些关于BindingContext如何工作的好例子:https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm

jecbmhm3

jecbmhm32#

根据你提供的代码,一切都是正确的。所以如果你确保属性会调用视图模型中的属性更改事件,你可以检查类似的情况,其中有一个例子展示了如何将自定义视图中的bindableproperty绑定到视图模型。
案例链接:Get value of a BindableProperty used in ViewModel in control?

yqyhoc1h

yqyhoc1h3#

所以,问题是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);

相关问题