首页 > 解决方案 > 如何在标签上为其他属性调用 PropertyChanged

问题描述

您好我很好奇是否可以设置PropertyChanged不同的属性?我的标签被绑定到Bandmember并且文本被绑定到一个名为FormattedName.

由于这是现在,它只会在属性更改PropertyChanged时运行此事件。FormattedName我有一个不同的属性调用HappinessBandmember我希望它调用PropertyChanged事件何时Happiness更新不FormattedName

XAML:

<ListView x:Name="dayView" ItemsSource="{Binding BandMembers}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*" />
                                </Grid.RowDefinitions>
                                <Label Grid.Column="0" x:Name="dayViewFormattedNameLabel" FontSize="Small" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"
                                       Text="{Binding FormattedName}" PropertyChanged="DayViewFormattedNameLabel_PropertyChanged" />
                                <Picker Grid.Column="1" FontSize="Small" Title="{Binding FormattedName, StringFormat='Select Task For {0}'}" x:Name="TaskPickerInListView" 
                                       ItemsSource="{Binding AvailableTasks}" SelectedItem="{Binding AssignedTask}" ItemDisplayBinding="{Binding TaskDescription}" 
                                       SelectedIndexChanged="TaskPickerUpdated" />
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

谢谢!

标签: c#xamarinbindinglabelpropertychanged

解决方案


啊,找到了你的新问题(我看到你意识到为什么它以前不起作用)

我建议改用值转换器

这将做的是将幸福的 int 值转换为颜色,然后您可以将Label'TextColor属性绑定到Happiness使用 an IntToColorConverter,例如:

public class IntToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double percent = (double)((int)value) / 100;
        double resultRed = Color.Red.R + percent * (Color.Green.R - Color.Red.R);
        double resultGreen = Color.Red.G + percent * (Color.Green.G - Color.Red.G);
        double resultBlue = Color.Red.B + percent * (Color.Green.B - Color.Red.B);
        return new Color(resultRed, resultGreen, resultBlue);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后在 XAML 中使用它:

<ContentPage.Resources>
    <ResourceDictionary>
        <local:IntToColorConverter x:Key="intToColor" />
    </ResourceDictionary>
</ContentPage.Resources>

<Label ... 
     TextColor="{Binding Happiness, Converter={StaticResource intToColor}}">

推荐阅读