【问题标题】:Unable to set bindings to BindableProperties in Partial Views using Xamarin Prism 7.1无法使用 Xamarin Prism 7.1 在部分视图中设置绑定到 BindableProperties
【发布时间】:2019-08-30 21:21:14
【问题描述】:

我在 Xamarin 中使用 Prism 7.1 的部分视图功能,其中 ContentView 可以拥有自己的 ViewModel。与视图模型的绑定工作正常。但是,我还想设置一个 BindableProperty。例如,我想在 ContentView 上设置一个 Title 属性。如果 ContentView 没有自己的 ViewModel,则绑定工作正常。如果它确实有自己的 ViewModel,则永远不会发生绑定。

MainPage.xaml
<controls:CustomContentView  Title="My Custom View Title"
    mvvm:ViewModelLocator.AutowirePartialView="{x:Reference self}"/>

CustomContentView.cs:
public static readonly BindableProperty TitleProperty = 
        BindableProperty.Create(
        nameof(Title),
        typeof(string),
        typeof(CustomContentView));

public string Title
{
    get => (string)GetValue(TitleProperty);
    set => SetValue(TitleProperty, value);
}

CustomContentView.xaml:
    <ContentView.Content>
      <StackLayout>
          <Label Text="{Title}" />
    </StackLayout>
</ContentView.Content>

如果我在 Title 的 set 方法上设置断点,它永远不会被命中,并且 Label 控件中的 Title 永远不会被绑定。

【问题讨论】:

    标签: xamarin view prism partial bindableproperty


    【解决方案1】:

    通过使用部分视图,您的绑定上下文是视图的视图模型,而不是视图本身...

    通过在 CustomContentView 中设置标签的文本,例如:

    <StackLayout>
      <Label Text="{Binding Title}" />
    </StackLayout>
    

    这应该会绑定到类似的东西:

    public class CustomContentViewModel : BindableBase
    {
        private string _title;
        public string Title
        {
            get => _title;
            set => SetProperty(ref _title, value);
        }
    }
    

    由于您希望绑定从后面的代码中提取,因此 XAML 需要类似于:

    <ContentView x:Class="AwesomeApp.Views.CustomContentView"
                 x:Name="self">
      <StackLayout>
        <Label Text="{Binding Title,Source={x:Reference self}}" />
      </StackLayout>
    </ContentView>
    

    【讨论】:

    • 标签源绑定到自己的工作完美。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    相关资源
    最近更新 更多