如果数据绑定值为true,则XAML更改按钮背景

时间:2017-08-02 12:58:59

标签: wpf xaml

如果background的属性为真,我试图更改button的{​​{1}}。

简要概述 - 我有一个data binding。我还给了ListBox这个项目的样式:

ListBox

现在,我想在这种风格中放一个按钮。所以,我使用了一个像ControlTemplate这样的东西(我知道这看起来很奇怪,我可以这样做的方式不同!):

  <ListBox Margin="0,5,0,0" Background="Transparent" 
             BorderThickness="0" 
             ItemsSource="{Binding PaymentsAndCollectionData.PaymentsToCreditors}"
             SelectedItem="{Binding PaymentsAndCollectionData.SelectedPaymentToCreditor}">
        <ListBox.ItemContainerStyle>
            .......
        </ListBox.ItemContainerStyle>
  </ListBox

所以,上面的工作正常。 <Style TargetType="ListBoxItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <Button> <Button.Style> <Style TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Button Name="Button" HorizontalContentAlignment="Stretch" Background="Transparent" BorderThickness="0" Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DataContext.PaymentsAndCollectionData.SelectPaymentToCreditorCommand}" CommandParameter="{Binding}"> <DockPanel Name="DP" LastChildFill="False" Background="{TemplateBinding Background}"> <TextBlock DockPanel.Dock="Left" Text="{Binding Name}" Margin="20,0,10,0" Padding="0,5,0,5" Foreground="{TemplateBinding Foreground}"/> <StackPanel Orientation="Horizontal" DockPanel.Dock="Right"> <TextBlock Text="R" VerticalAlignment="Center" Foreground="{TemplateBinding Foreground}"/> <TextBlock Text="{Binding Amount, StringFormat=N2}" VerticalAlignment="Center" Margin="0,0,10,0" Foreground="{TemplateBinding Foreground}"/> </StackPanel> </DockPanel> </Button> <ControlTemplate.Triggers> <DataTrigger Binding="{Binding IsSelected}" Value="True"> <Setter TargetName="DP" Property="Background" Value="{StaticResource APPLICATION_GREEN_COLOR}" /> <Setter Property="Foreground" Value="White" /> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Button.Style> </Button> </ControlTemplate> </Setter.Value> </Setter> </Style> Name是从Amount设置的。我只是没有设置DataBinding,如果backgroundIsSelected

我的绑定对象如下所示:

true

1 个答案:

答案 0 :(得分:1)

如果在创建对象后更改IsSelected属性,则需要在此对象中实现INotifyPropertyChanged接口以使Binding工作。

public class PaymentItem : INotifyPropertyChanged
{
    private bool _isSelected;

    public string Name { get; set; }

    public decimal Amount { get; set; }

    public bool IsSelected
    {
        get
        {
            return _isSelected;
        }
        set
        {
            _isSelected = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

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