按钮内容不会实时更改
本文关键字:实时 按钮 | 更新日期: 2023-09-27 18:16:16
我有一个按钮。我希望它是一个喜欢的切换按钮在一个列表框。参见下面的代码:
<Page
x:Class="W.Pages.ExPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Workout_EF.Pages"
xmlns:converter="using:W.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:data="using:W.Model"
mc:Ignorable="d">
<Page.Resources>
<converter:FavoriteValueConverter x:Key="favoriteConverter" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListBox Name="MyListbox"
SelectionMode="Single"
ItemsSource="{x:Bind exs}"
SelectionChanged="MyListbox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="data:Ex">
<StackPanel Orientation="Horizontal">
<Button Name="IsFavoriteToggle" Click="IsFavoriteToggle_Click">
<Button.Content>
<TextBlock
x:Name="isFavoriteTextBlock"
Text="{x:Bind IsFavorite, Converter={StaticResource favoriteConverter}}"
FontFamily="Segoe MDL2 Assets"/>
</Button.Content>
</Button>
<TextBlock
VerticalAlignment="Center"
FontSize="16"
Text="{Binding ExName}"
Margin="20,0,0,0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Page>
我的问题是,当我点击这个按钮,它不改变它的图标(从空星到全星,反之亦然)在实时。
如果列表框将再次加载,则显示正确的图标。
后面的代码是:
namespace W.Pages
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ExPage : Page
{
ObservableCollection<Exs> exs = new ObservableCollection<Exs>();
public ExPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
List<Exs> tmpEx = e.Parameter as List<Exs>;
foreach (Exs item in tmpEx)
{
exs.Add(item);
}
}
private void IsFavoriteToggle_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
int index = MyListbox.Items.IndexOf(button.DataContext);
Ex ex = (Exs)MyListbox.Items[index];
DAL.SetToFavorite(ex, !ex.IsFavorite);
}
}
}
我注意到itemsource可能有一些问题。它需要在点击按钮后更改其内容。
这是每个人都会犯的一个常见错误,那就是ObservableCollection<T>
实际上通知了绑定器集合中的更改,而不是集合中的对象。你有一个IsFavorite
属性在你的Esx
类按钮需要知道的变化,但Esx
需要实现INotifyPropertyChanged
看到这个,如果你需要更多的帮助,张贴代码为Esx类也许我们可以帮助。
正如Emaud所说,您必须在Esx
类中实现INotifyPropertyChanged
接口。你还必须在你的绑定中设置Mode
为OneWay
,因为x:Bind
的默认模式是OneTime
,所以它不监听任何更改。
Text="{x:Bind IsFavorite, Mode=OneWay, Converter={StaticResource favoriteConverter}}"