XAML Xamarin窗体使用自定义ControlTemplate覆盖选取器

fjnneemd  于 2022-12-31  发布在  其他
关注(0)|答案(1)|浏览(132)

我想重写Xamarin窗体控件选择器,以便在绑定的集合为空时显示"No entries"。
我试过:

<Picker
    x:Class="v.App.Styling.Controls.vPicker"
    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"
    xmlns:controls="clr-namespace:v.App.Styling.Controls;assembly=v.App"
    x:Name="CustomPicker"
    mc:Ignorable="d" >

    <Picker.Style>
        <Style TargetType="controls:vPicker">
            <Setter Property="ControlTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <controls:vStackLayout >
                            <ContentPresenter 
                                IsVisible="{Binding ItemsSource.Count, Converter={StaticResource HasItemsToBoolConverter}, ConverterParameter=0}"
                                Content="{TemplateBinding Content}" />

                            <controls:vEntry 
                                IsVisible="{Binding ItemsSource, Converter={StaticResource HasNoItemsToBoolConverter}"
                                IsEnabled="False"
                                TextColor="{StaticResource ColorTextSecondary}"
                                Text="No entries"  />
                        </controls:vStackLayout>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Picker.Style>
</Picker>

但我得到

Error XFC0001: Cannot resolve property "ControlTemplate" on type "vPicker (property missing or missing accessors)". (13, 21)

我不知道我做错了什么...

dhxwm5r4

dhxwm5r41#

你可以用数据绑定来实现。
在选取器的. xaml中:

<Picker x:Name="picker"
        ItemsSource="{Binding ItemCollection}"
        IsVisible="{Binding IsVisible}"
        Title="Select a monkey"
        TitleColor="Red">         
</Picker>

在ViewModel中添加一些逻辑,如下所示:

public Command ClickedCommand  // i define a button to add item to ItemCollection as a demo
{
    get
    {
        return new Command(() =>
        {
            ItemCollection.Add(count);
            count++;
            if(ItemCollection.Count > 0)
            {
                IsVisible = true;
            }
        });
    }
}

希望对你有用。

相关问题