c# - WPF:未调用 IValueConverter

标签 c# wpf button converters

我正在尝试根据 ObservableCollection 的“已更改”条件更改按钮的“背景”。我的 ViewModel 上有一个“IsDirty” bool 属性,我确信它会在 ObservableCollection 更改时更新。

但是,按钮的背景没有改变,而且似乎从未调用过“Convert”方法。

我的转换器缺少什么?当 ObservableCollection 改变时按钮的背景应该变成红色(IsDirty 为真)

编辑

我更新了转换器以返回红色或绿色的值(而不是红色和透明)并且按钮没有背景颜色,所以这会告诉我永远不会调用转换器。

编辑 2

添加了显示 IsDirty 属性的 ViewModel 代码。

转换器

public class IsDirtyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return System.Convert.ToBoolean(value) ?
            new SolidColorBrush(Colors.Red)
            : new SolidColorBrush(Colors.Green);
    }

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

}

查看

<Window x:Class="SerializeObservableCollection.MainWindow"
        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"
        xmlns:conv="clr-namespace:SerializeObservableCollection.Converter"
        xmlns:ignore="http://www.ignore.com"
        mc:Ignorable="d ignore"
        Height="300"
        Width="491"
        Title="MVVM Light Application"
        DataContext="{Binding Main, Source={StaticResource Locator}}">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Skins/MainSkin.xaml" />
            </ResourceDictionary.MergedDictionaries>

            <conv:IsDirtyConverter x:Key="IsDirtyConverter" />

        </ResourceDictionary>
    </Window.Resources>

    <Grid x:Name="LayoutRoot">

        <TextBlock FontSize="36"
                   FontWeight="Bold"
                   Foreground="Purple"
                   Text="{Binding WelcomeTitle}"
                   VerticalAlignment="Top"
                   TextWrapping="Wrap" Margin="10,10,10,0" Height="54" HorizontalAlignment="Center" />

        <DataGrid Margin="10,69,10,38"
                  ItemsSource="{Binding CodeCollection, Mode=TwoWay}"/>
        <Button Name="SaveButton" Content="Save" 
                Command="{Binding SaveButtonClickedCommand}"
                Background="{Binding 
                                RelativeSource={RelativeSource Self},
                                Path=IsDirty, 
                                UpdateSourceTrigger=PropertyChanged, 
                                Converter={StaticResource IsDirtyConverter}}"
                HorizontalAlignment="Right" Margin="0,0,90,10" 
                Width="75" Height="20" 
                VerticalAlignment="Bottom"/>
        <Button Content="Refresh" HorizontalAlignment="Right" Margin="0,0,10,10" Width="75"
                Command="{Binding RefreshButton_Click}" Height="20" VerticalAlignment="Bottom"/>

    </Grid>
</Window>

查看模型

public class MainViewModel : ViewModelBase
{
    public bool IsDirty;


    /// <summary>
    /// ObservableCollection of Codes
    /// </summary>
    private const string CodeCollectionPropertyName = "CodeCollection";
    private ObservableCollection<Code> _codeCollection;
    public ObservableCollection<Code> CodeCollection
    {
        get
        {
            if (_codeCollection == null)
            {
                _codeCollection = new ObservableCollection<Code>();
            }
            return _codeCollection;
        }
        set
        {
            if (_codeCollection == value)
            {
                return;
            }

            _codeCollection = value;
            RaisePropertyChanged(CodeCollectionPropertyName);
        }
    }



    /// <summary>
    /// Initializes a new instance of the MainViewModel class.
    /// </summary>
    public MainViewModel(IDataService dataService)
    {
         // Load XML file into ObservableCollection
        LoadXML();
    }

    private void LoadXML()
    {
        try
        {
            XmlSerializer _serializer = new XmlSerializer(typeof(Codes));

            // A file stream is used to read the XML file into the ObservableCollection
            using (StreamReader _reader = new StreamReader(@"LocalCodes.xml"))
            {
                CodeCollection = (_serializer.Deserialize(_reader) as Codes).CodeCollection;

            }

            // Change notification setup
            CodeCollection.CollectionChanged += OnCodeCollectionChanged;

        }
        catch (Exception ex)
        {
            // Catch exceptions here
        }

    }

    private void SaveToXML()
    {
        try
        {
            XmlSerializer _serializer = new XmlSerializer(typeof(ObservableCollection<Code>));
            using (StreamWriter _writer = new StreamWriter(@"LocalCodes.xml"))
            {
                _serializer.Serialize(_writer, CodeCollection);
            }
        }
        catch (Exception ex)
        {

        }
    }

    private RelayCommand _saveButtonClickedCommand;
    public RelayCommand SaveButtonClickedCommand
    {
        get
        {
            return _saveButtonClickedCommand ??
                (_saveButtonClickedCommand = new RelayCommand(
                    () => 
                    {
                        SaveButtonClicked(); 
                    }));

        }
    }
    private void SaveButtonClicked()
    {
        SaveToXML();
    }

    private void OnCodeCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        IsDirty = true;         
    }
}

最佳答案

从您的绑定(bind)中删除 RelativeSource={RelativeSource Self}。此代码在 Button 中而不是在其 DataContext 中进行绑定(bind)搜索 IsDirty。

            Background="{Binding 
                        Path=IsDirty, 
                        UpdateSourceTrigger=PropertyChanged, 
                        Converter={StaticResource IsDirtyConverter}}"

或使用

               Background="{Binding 
                        RelativeSource={RelativeSource Self},
                        Path=DataContext.IsDirty, 
                        UpdateSourceTrigger=PropertyChanged, 
                        Converter={StaticResource IsDirtyConverter}}"

另外 IsDirty 应该是不可变的属性

 private bool _isDirty;
 public bool IsDirty
        get
        {

            return _isDirty;
        }
        set
        {
            _isDirty = value

            _codeCollection = value;
            RaisePropertyChanged("IsDirty");
        }

关于c# - WPF:未调用 IValueConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19453568/

相关文章:

c# - 将 EAP 复制到我的 sql 数据库 : using C# Addin

c# - 我如何在 pcap.net 中获取所选设备的 MAC 地址

javascript - 提交按钮无法正常工作

html - 如何在一行中水平对齐 css/html 中的按钮?

html - 将 Dojo 样式应用于按钮时显示的两个按钮

c# - 基于声明的表单例份验证角色

c# - .NET 与 RDP 连接

c# - 从ViewModel(MVVM)添加到XAML WPF

c# - 窗口关闭后无法设置可见性或调用 Show、ShowDialog 或 EnsureHandle

c# - WPF中页面 View 模型的依赖注入(inject)