IValueConverter.单向绑定不会调用Convert
本文关键字:调用 Convert 绑定 IValueConverter | 更新日期: 2023-09-27 17:49:14
我有一个布尔属性(在setter中称为INotifyPropertyChanged
),它被绑定到一个按钮。我的XAML中的IsEnabled属性。目前我正在使用TwoWay
绑定,但这会导致问题,我只需要OneWay
绑定。我的问题是,我使用的转换器不被调用超出第一次程序启动。我在setter中放置了断点,它被调用load,但是Convert()
方法根本没有被调用。为什么会这样?
public bool IsSaving
{
get
{
return _isSaving;
}
set
{
_isSaving = value;
NotifyOfPropertyChange(() => IsSaving);
}
}
和XAML:
IsEnabled="{Binding Path=IsSaving, Mode=OneWay, Converter={StaticResource booleanToNotEnabledConverter}}"
转换器实际上只是返回!(bool)value
,所以当IsSaving
为真时按钮被禁用
运行时的一些更改可能会导致绑定中断(因为您绑定到DataContext +一个相对路径),如果您使用Visual Studio,请确保检查Output-window是否有任何绑定错误。
编辑:由于没有注意到:这是一个标准绑定,发布的代码没有任何问题,问题必须由上下文引起。
下面是我使用的代码,它可以工作:
转换器:
using System.Windows.Data;
using System;
namespace SilverlightApplication1
{
public class BooleanToNotEnabledConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
XAML:
<UserControl x:Class="SilverlightApplication1.MainPage"
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:local="clr-namespace:SilverlightApplication1"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<UserControl.Resources>
<local:BooleanToNotEnabledConverter x:Key="booleanToNotEnabledConverter" />
</UserControl.Resources>
<StackPanel Margin="100">
<Button Content="Flip"
Click="Button_Click" />
<TextBlock Text="{Binding IsSaving}"
Height="20" />
<Button IsEnabled="{Binding IsSaving, Mode=OneWay, Converter={StaticResource booleanToNotEnabledConverter}}"
Content="Some Button" />
</StackPanel>
</UserControl>
背后的代码:
using System.Windows.Controls;
using System.Windows;
using System.ComponentModel;
namespace SilverlightApplication1
{
public partial class MainPage : UserControl
{
private Data _data;
public MainPage()
{
InitializeComponent();
_data = new Data { IsSaving = true };
this.DataContext = _data;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
_data.IsSaving = !_data.IsSaving;
}
}
public class Data : INotifyPropertyChanged
{
#region IsSaving Property
private bool _isSaving;
public bool IsSaving
{
get
{
return _isSaving;
}
set
{
if (_isSaving != value)
{
_isSaving = value;
OnPropertyChanged("IsSaving");
}
}
}
#endregion
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var p = PropertyChanged;
if (p != null)
{
p(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
您确定使用正确的字符串调用PropertyChanged事件处理程序吗?
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("IsSaving"));