我在后面的代码中定义了以下ObservableDictionary(这不是MVVM应用程序:-(而且我没有写)。
视图代码背后的类将构造函数中的DataContext设置为DataContext = this。
public ObservableDictionary<string, PhaseGroupBoxWrapper> PhasesGridDictionary { get; set; } = new ObservableDictionary<string, PhaseGroupBoxWrapper>();
PhaseGroupBoxWrapper的定义如下:
public class PhaseGroupBoxWrapper : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private bool _isHidden;
public bool IsHidden
{
get { return _isHidden; }
set
{
_isHidden = value;
OnPropertyChanged("IsHidden");
}
}
}
我有一个按钮,它是单击鼠标右键菜单的一部分,并在视图中定义如下: 请注意,在“样式”部分中,我具有由DataTrigger和转换器生成的Button内容。
<Button
Tag="ToggleVisButton"
Margin="2"
Command="{Binding GroupBoxTogglePhaseVisibility}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource PhaseEditMultiParamConverter}">
<Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Tag"/>
<Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Header"/>
</MultiBinding>
</Button.CommandParameter>
<Button.Style>
<Style TargetType="Button">
<Setter Property="Content" Value="Show Phase"/>
<Style.Triggers>
<DataTrigger Value="False">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource PhaseHideShowButtonContentConverter}">
<Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Tag"/>
<Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Header"/>
<Binding Path="PhasesGridDictionary"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Content" Value="Hide Phase"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
....并且转换器定义为:
public class PhaseHideShowButtonContentConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
bool retVal = false;
if ((string)values[0] != String.Empty)
{
string[] calibrationInfo = ((string)values[0]).Split(' ');
string controllerName = calibrationInfo[0];
string calibrationName = calibrationInfo[2];
string phaseName = (string)values[1];
ObservableDictionary<string, PhaseGroupBoxWrapper> PhasesGridDictionary = (ObservableDictionary<string, PhaseGroupBoxWrapper>)values[2];
string dictionaryKey = controllerName + " - " + calibrationName + " - " + phaseName;
retVal = PhasesGridDictionary[dictionaryKey].IsHidden;
}
return retVal;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
我遇到的问题是,启动时正确设置了按钮内容。如果后来为PhaseGroupBoxWrapper IsHidden属性分配了一个不同的值,则将调用setter,但在OnPropertyChanged函数中,PropertyChanged 的值始终为空 ,这将导致Button DataTrigger不被解雇。
有人可以解释为什么PropertyChanged值始终为空吗?
非常感谢您的帮助!