在xaml属性中使用不同的数据类型

5cnsuln7  于 2022-12-25  发布在  其他
关注(0)|答案(2)|浏览(134)
<Picker
            Title="Select a Profile"
            ItemsSource="{Binding ProfileManager.Profiles}" 
            ItemDisplayBinding="{Binding Name}"
            SelectedItem="{Binding SelectedProfile, Mode=TwoWay}"
            HorizontalOptions="CenterAndExpand"
            VerticalOptions="CenterAndExpand"
            SelectedIndex="1"
            HeightRequest="200"
            WidthRequest="325"
            Margin="10"
            BackgroundColor="{StaticResource Secondary}">
        </Picker>

itemSource属性具有x:DataType="ViewModels:ParametersViewModel"数据类型,但是ItemDisplayBinding具有x:DataType="Models:Profile"数据类型。
我怎样才能分别定义这些数据类型?

aelbi1ox

aelbi1ox1#

从文档Populate a Picker with data using data binding中,我们可以发现
还可以使用数据绑定将Picker的ItemsSource属性绑定到IList集合,从而用数据填充Picker。

<Picker Title="Select a monkey"
        ItemsSource="{Binding Monkeys}"
        ItemDisplayBinding="{Binding Name}" />

绑定到对象列表时,必须告知选取器要显示每个对象的哪个属性。这可以通过将每个对象的ItemDisplayBinding属性设置为required属性来实现。在上面的代码示例中,选取器设置为显示每个Monkey.Name属性值。
因此,上面代码中的ItemDisplayBinding属性(Name)应该是ItemsSourceProfileManager.Profiles)中每个对象(Profile)的必需属性。
实际上,我们不必也不需要为Picker指定所谓的x:DataType

    • 注:**

您可以在这里找到MonkeyAppPicker的官方示例,虽然它是用xamarin编写的,但在MAUI上的实现几乎是相同的。

xe55xuns

xe55xuns2#

不确定这个答案是否适合您,但是您可以通过澄清Ancestor Type在同一个XAML文件中定义不同的数据类型。

<ContentPage 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:Models="clr-namespace:Models"
    xmlns:ViewModels="clr-namespace:ViewModels" 
    x:DataType="viewmodel:ParametersViewModel">

    <Picker ItemsSource="{Binding ProfileManager.Profiles}" 
            ItemDisplayBinding="{Binding Source={RelativeSource AncestorType={x:Type Models:Profile}}, Path=Name}"/>
</ContentPage>

一旦在根中设置了DataType(在本例中为ContentPage),默认情况下其子级的所有绑定都将转到该数据类型。

相关问题