我有这个简单的控制:
<UserControl x:Class="MyProject.Controls.ImageToggleButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="480"
d:DesignWidth="480"
Loaded="OnLoaded"
Tap="OnTap"
Background="{x:Null}">
<Image x:Name='ButtonImage' />
</UserControl>
后面的代码:
public partial class ImageToggleButton
{
public static readonly DependencyProperty CheckedImageProperty = DependencyProperty.Register("CheckedImage", typeof(ImageSource), typeof(ImageToggleButton), new PropertyMetadata(default(ImageSource), OnPropertyChanged));
public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register("IsChecked", typeof(bool), typeof(ImageToggleButton), new PropertyMetadata(default(bool), OnPropertyChanged));
public static readonly DependencyProperty UncheckedImageProperty = DependencyProperty.Register("UncheckedImage", typeof(ImageSource), typeof(ImageToggleButton), new PropertyMetadata(default(ImageSource), OnPropertyChanged));
public ImageToggleButton()
{
this.InitializeComponent();
}
public ImageSource CheckedImage
{
get { return (ImageSource)this.GetValue(CheckedImageProperty); }
set { this.SetValue(CheckedImageProperty, value); }
}
public bool IsChecked
{
get { return (bool)this.GetValue(IsCheckedProperty); }
set { this.SetValue(IsCheckedProperty, value); }
}
public ImageSource UncheckedImage
{
get { return (ImageSource)this.GetValue(UncheckedImageProperty); }
set { this.SetValue(UncheckedImageProperty, value); }
}
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((ImageToggleButton)d).UpdateImage();
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
this.UpdateImage();
}
private void OnTap(object sender, GestureEventArgs e)
{
this.IsChecked = !this.IsChecked;
}
private void UpdateImage()
{
this.ButtonImage.Source = this.IsChecked ? this.CheckedImage : this.UncheckedImage;
}
}
此控件包含在另一个UserControl
用作 的DataTemplate
中LongListSelector.ItemTemplate
。
(Some xaml snipped for brevity...)
<UserControl ...>
<Grid>
<controls:ImageToggleButton Grid.Column="0"
CheckedImage="/Assets/icon_checked.png"
UncheckedImage="/Assets/icon_unchecked.png"
IsChecked="{Binding Store.IsSelected}"
Height="48" />
</Grid>
</UserControl>
这DataContext
是一个带有Store
成员的视图模型,其中Store
是一个类型的对象:
public class Store : NotificationObject
{
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set { this.Set(() => IsSelected, ref IsSelected, value); }
}
}
我的问题是,当为父控件LongListSelector
设置新值时,图像上的值不会正确更新。DataContext
IsChecked