Связывание преобразователя цвета не вызывается - PullRequest
2 голосов
/ 16 октября 2019

У меня есть метка с черным цветом текста внутри рамки с белым фоновым цветом, дело в том, что я хочу назначить цвет фона и цвет текста из модели представления, я создал конвертер и сделал привязки, но дляпо какой-то причине он не работает

это мой код просмотра:

?xml version="1.0" encoding="UTF-8"?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="ComanderoMovil.Views.PlatillosView"
    xmlns:ios="clr -namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
    ios:Page.UseSafeArea="true"
    xmlns:behaviorsPack="clr- namespace:Xamarin.Forms.BehaviorsPack;assembly=Xamarin.Forms.Behaviors Pack"
    xmlns:converterPack="clr-namespace:ComanderoMovil.Converters">

    <ContentPage.Resources>
        <ResourceDictionary>
            <converterPack:ColorConverter x:Key="ColorConverter"/>
        </ResourceDictionary>
    </ContentPage.Resources>

    <ContentPage.Content>
        <StackLayout>
            <SearchBar> </SearchBar>
            <CollectionView ItemsSource="{Binding Grupos}"
                            HeightRequest="50"
                            ItemsLayout="HorizontalList"
                            SelectionMode="Single"
                            SelectionChangedCommand="{Binding 
SelectedGrupoCommand, Mode=TwoWay}">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <ContentView Padding="2">
                            <Frame BorderColor="Black"
                                   HasShadow="False"
                                   Padding="2"
                                   BackgroundColor="{Binding 
ButtonBackColor, Converter={StaticResource ColorConverter}}">
                                <StackLayout>
                                    <Label Margin="10"
                                           Text="{Binding nombre}"
                                           TextColor="{Binding 
TextColor, Converter = {StaticResource ColorConverter}}"

VerticalTextAlignment="Center"

 HorizontalTextAlignment="Center"
                                           FontSize="Small"

VerticalOptions="CenterAndExpand"></Label>
                                </StackLayout>
                            </Frame>
                         </ContentView>
                     </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
 </ContentPage.Content>
</ContentPage>

Вот мой ViewModel:

public class PlatillosViewModel : INotifyPropertyChanged
{
    private INavigation Navigation;
    private ObservableCollection<PlatilloModel> _platillos;
    private string _textColor;
    private string _backColor;
    public event PropertyChangedEventHandler PropertyChanged;
    public ObservableCollection<GrupoModel> Grupos { get; set; }
    public ObservableCollection<PlatilloModel> Platillos
    {
        get => _platillos;
        set
        {
            _platillos = value;
            OnPropertyChanged();
        }
    }

    public string TextColor
    {
        get => _textColor;
        set
        {
            _textColor = value;
            OnPropertyChanged();
        }
    }

    public string ButtonBackColor
    {
        get => _backColor;
        set
        {
            _backColor = value;
            OnPropertyChanged();
        }
    }

    public PlatillosViewModel(INavigation navigation)
    {
        Navigation = navigation;
        TextColor = "Black";
        ButtonBackColor = "White";
        PlatillosRepository repository = new PlatillosRepository();
        Platillos = repository.GetAll();
        GrupoRepository grupoRepository = new GrupoRepository();
        Grupos = grupoRepository.GetAll();
    }

    public ICommand SelectedPlatilloCommand => new Command<PlatilloModel>(async platillo =>
    {
        await Navigation.PushAsync(new PlatilloView());
    });

    public ICommand SelectedGrupoCommand => new Command<GrupoModel>(async grupo =>
    {
        ButtonBackColor = "Black";
        TextColor = "White";
        PlatillosRepository platillosRepository = new PlatillosRepository();
        Platillos = platillosRepository.GetFilteredByGroup(grupo);
    });

    protected virtual void OnPropertyChanged([CallerMemberName] string property = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
}

и вот мой конвертер:

public class ColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var valor = value.ToString();
        switch(valor)
        {
            case "White":
                return Color.White;
            case "Black":
                return Color.Black;
            default:
                return Color.Red;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

1 Ответ

2 голосов
/ 16 октября 2019

Ваша проблема не с ValueConverter, а с вашими привязками.

<CollectionView ItemsSource="{Binding Grupos}"
                HeightRequest="50"
                ItemsLayout="HorizontalList"
                SelectionMode="Single"
                SelectionChangedCommand="{Binding SelectedGrupoCommand, Mode=TwoWay}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <ContentView Padding="2">
                <Frame BorderColor="Black"
                        HasShadow="False"
                        Padding="2"
                        BackgroundColor="{Binding ButtonBackColor, Converter={StaticResource ColorConverter}}">
                    <StackLayout>
                        <Label Margin="10"
                                Text="{Binding nombre}"
                                TextColor="{Binding TextColor, Converter = {StaticResource ColorConverter}}"
                                VerticalTextAlignment="Center"
                                HorizontalTextAlignment="Center"
                                FontSize="Small"
                                VerticalOptions="CenterAndExpand">
                        </Label>
                    </StackLayout>
                </Frame>
                </ContentView>
            </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

Вы используете CollectionView и когда вы устанавливаете ItemSource

<CollectionView ItemsSource="{Binding Grupos}"

Всепривязки, которые вы делаете внутри, примут это как BindingContext.

<Label Margin="10"
        Text="{Binding nombre}"
        TextColor="{Binding TextColor, Converter = {StaticResource ColorConverter}}"
        VerticalTextAlignment="Center"
        HorizontalTextAlignment="Center"
        FontSize="Small"
        VerticalOptions="CenterAndExpand" />

Точно так же, как свойство nombre , которое вы связываете со свойством Label Text, является частью класса GroupModel, то есть TextColor иОжидается, что ButtonBackColor свойства будут частью того же класса, который вы связали с ItemSource.

Если вы хотите, чтобы это работало: либо добавьте эти два свойства (TextColor и ButtonBackColor) кGroupModel классифицируйте или измените привязку так, чтобы к этим двум свойствам обращались из родительской привязки.

Первое даст вам большую гибкость, но в то же время может добавить повторяющийся код (если все элементы будут совместно использоватьсянапример, того же цвета).

Второй вариант может быть выполнен следующим образом:

Добавьте имя к CollectionView

<CollectionView ItemsSource="{Binding Grupos}"
                HeightRequest="50"
                x:Name="GruposList"
               ....

Тогда мы изменимнемного привязка тех элементов, которые не являются частью вашего GrupoModel, но являются частью ViewModel

<DataTemplate>
    <ContentView Padding="2">
        <Frame BorderColor="Black"
                HasShadow="False"
                Padding="2"
                BackgroundColor="{Binding BindingContext.ButtonBackColor, 
                                  Source={x:Reference GruposList}, 
                                  Converter={StaticResource ColorConverter}}">
            <StackLayout>
                <Label Margin="10"
                        Text="{Binding nombre}"
                        TextColor="{Binding BindingContext.TextColor, 
                                    Source={x:Reference GruposList}, 
                                    Converter={StaticResource ColorConverter}}"
                        VerticalTextAlignment="Center"
                        HorizontalTextAlignment="Center"
                        FontSize="Small"
                        VerticalOptions="CenterAndExpand">
                </Label>
            </StackLayout>
        </Frame>
    </ContentView>
</DataTemplate>

Как вы можете видеть, мы теперь получаем доступ к ним через привязку CollectionView, мы делаем это, когда мыуказать источник и использоватьReference. Подробнее о привязках здесь

Надеюсь, это поможет .-

Side Примечание:

В вашем конвертере следите за null .

var valor = value.ToString();

Вышеуказанное может привести к сбою приложения, если значение равно нулю.

Используйте это вместо:

var valor = value?.ToString();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...