在我的应用中,有一个选项,用户可以将项目添加到他们的收藏夹列表中。
该按钮包含一个爱情符号。我要在收藏夹列表中已有商品时更改颜色。
我尝试过这种方法,但是它不起作用,因为按钮是GridView项。
private void OrdersButton_Click(object sender, EventArgs e)
{
if (OrdersButton.Text == "Turn Orders On")
{
OrdersButton.Text = "Turn Orders Off";
}
else if (OrdersButton.Text == "Turn Orders Off")
{
OrdersButton.Text = "Turn Orders On";
}
}
[此帖子的答案-Change button text after click, then change it back after clicking again]
这是我的按钮代码-
<Button Style="{StaticResource TextBlockButtonStyle}"
Margin="2,0"
Content=""
FontFamily="Segoe MDL2 Assets"
x:Name="addToFevBtn"
Click="AddToFevBtn_Click"/>
所以我的问题是我该怎么做?
答案 0 :(得分:1)
根据您的要求,更好的方法是将绑定按钮的Foreground
属性的值为Boolean
,然后使用IValueConverter
将其转换为SolidColorBrush
。您可以通过在按钮单击方法中修改IsFav
的值来更改符号的颜色。
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
public List<Item> Items { get; set; }
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
Items = new List<Item>();
Items.Add(new Item { Name = "Nice Day", IsFav = true });
Items.Add(new Item { Name = "Nice Day", IsFav = false });
Items.Add(new Item { Name = "Nice Day", IsFav = false });
}
private void AddToFevBtn_Click(object sender, RoutedEventArgs e)
{
var btn = sender as Button;
var item = btn.DataContext as Item;
item.IsFav = !item.IsFav;
}
}
public class Item : INotifyPropertyChanged
{
public bool IsFav
{
get
{
return isFav;
}
set
{
isFav = value;
OnPropertyChanged();
}
}
private bool isFav;
public string Name { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
// Raise the PropertyChanged event, passing the name of the property whose value has changed.
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (Boolean.Parse(value.ToString()))
{
return new SolidColorBrush(Colors.Red);
}
else
{
return new SolidColorBrush(Colors.Black);
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Xaml
<Page.Resources>
<local:ColorConverter x:Key="Converter"/>
</Page.Resources>
<Grid>
<GridView ItemsSource="{x:Bind Items}">
<GridView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Width="100" >
<TextBlock Text="{Binding Name}"
TextAlignment="Center"
HorizontalAlignment="Center"
Margin="0,10,0,0"/>
<Button Style="{StaticResource TextBlockButtonStyle}"
HorizontalAlignment="Center"
Margin="0,30,0,0"
Content=""
FontSize="25"
FontFamily="Segoe MDL2 Assets"
Foreground="{Binding IsFav,Converter={StaticResource Converter}}"
Click="AddToFevBtn_Click"
x:Name="addToFevBtn"
/>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>