我的任务是在用户点击按钮时更改StackPanel的可见性,由于该按钮的值,此StackPanel可以具有特殊功能。出于这个原因,我实现了VisibilityConverter,它应该在StackPanelVis为true时改变可见性。转换器代码:
public class StakPanelToVisible : IValueConverter
{
public static bool StackPanelVis;
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
value = StackPanelVis;
return (bool)value ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(...) {empty}
当用户按下cause命令中的按钮时,将值传递给VM中的命令StackPanelToVisible代码:
public RelayCommand SetAddingButton
{
get
{
return new RelayCommand(SetAddingProperties, true);
}
}
public bool StackPanelVis { get; private set; }
private void SetAddingProperties()
{
TextInducator = "Add";
StakPanelToVisible.StackPanelVis = true;
}
XAML中的视图代码:
<StackPanel Margin="5 10 5 0" Grid.Column="1" >
<StackPanel Visibility="{Binding StackPanelVis, Converter=
{StaticResource StakPanelToVisible}}" >
some elements in StackPanel
<Button Content="Add" Margin="5 5 5 1"
Padding="2" x:Name="AddPosition_button"
Command="{Binding SetAddingButton }"/>
最后一个按钮应该改变StackPanel的可见性。但是,这段代码不起作用。它为什么不起作用?还有其他任何可以帮助我的版本吗?非常感谢任何有关此任务的帮助,文章或替代解决方案。
答案 0 :(得分:1)
您的VM中有StackPanelVis属性,但更改了转换器中的静态字段。
首先,您需要将其从转换器中删除。
public class StakPanelToVisible : IValueConverter
{
// public static bool StackPanelVis; // remove this one
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
// value = StackPanelVis; // and this one
return (bool)value ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(...) {empty}
}
其次,更改命令实现以更改VM中的属性。
private void SetAddingProperties()
{
TextInducator = "Add";
StackPanelVis = true;
}
第三,在你的StackPanelVis中调用OnPropertyChanged(&#34; StackPanelVis&#34;):
private bool _stackPanelVis;
public bool StackPanelVis
{
get { return _stackPanelVis; }
set {
if (value == _stackPanelVis) return;
_stackPanelVis = value;
OnProperyChanged("StackPanelVis");
}
}
您的VM必须实现INotifyPropertyChanged接口。
此外,您可以使用内置BooleanToVisibilityConverter
答案 1 :(得分:0)
您的转换器应如下所示:
class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is Boolean && (bool)value)
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is Visibility && (Visibility)value == Visibility.Visible)
{
return true;
}
return false;
}
}
并且应该在App.xaml或您要使用它的文件中引用(下面是App.xaml的实现)
<ResourceDictionary>
<local:BooleanToVisibilityConverter x:Key="StakPanelToVisible" />
</ResourceDictionary>
此外,您的StackPanelVis属性应该实现INotifyPropertyChanged接口,以便让View知道它已从代码中更改(它应该看起来更像这样):
private bool isStackPanelVisible;
public bool IsStackPanelViesible
{
get { return isStackPanelVisible; }
set
{
isStackPanelVisible = value;
//RaisePropertyChanged from your implementation of INotifyPropertyChanged
}
}