我需要帮助,因为我有一个UserControl,“myUC”,我想在我按下MenuItem时更改其可见性。我遵循BoolToVisibilityConverter类:
[ValueConversion(typeof(bool), typeof(Visibility))]
public sealed class BoolToVisibilityConverter : IValueConverter
{
public Visibility TrueValue { get; set; }
public Visibility FalseValue { get; set; }
public BoolToVisibilityConverter()
{
// set defaults
TrueValue = Visibility.Visible;
FalseValue = Visibility.Collapsed;
}
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (!(value is bool))
return null;
return (bool)value ? TrueValue : FalseValue;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (Equals(value, TrueValue))
return true;
if (Equals(value, FalseValue))
return false;
return null;
}
}
我在Windows.Resource中将我的转换器设置为StaticResource
<Window.Resources>
<vs:BoolToVisibilityConverter x:Key="VisibilityConverter" TrueValue="Visible" FalseValue="Hidden" />
</Window.Resources>
当我在XAML中调用用户控件时,我添加了转换器
<uc:Add Visibility="{Binding MyProperty,Converter={StaticResource VisibilityConverter},FallbackValue=Hidden}" />.
我绑定了属性“MyProperty”所以:
private bool _myProperty;
public bool MyProperty
{
get {
return _myProperty;
}
set {
if (_myProperty== true)
_myProperty= value;
else
_myProperty= true;
OnPropertyChanged("MyProperty");
}
}
但是当我启动应用程序时,它不会改变UserControl的可见性。
我忘了提到我使用ICommand
的MenuItem bindig <MenuItem Name="mnuAggiungi" Header="_Aggiungi" Command="{Binding MyCommand}"/>
RelayCommand _add;
public ICommand MyCommand
{
get
{
if (_add == null) _add = new RelayCommand(param => this.MyCommandUC());
return _add;
}
}
public void MyCommandUC()
{
}
我忘了提到我使用ICommand
的MenuItem bindigMenuItem Name =“mnuAggiungi”Header =“_ Aggiungi”Command =“{Binding MyCommand}”
RelayCommand _add;
public ICommand MyCommand
{
get
{
if (_add == null) _add = new RelayCommand(param => this.MyCommandUC());
return _add;
}
}
public void MyCommandUC()
{
}
答案 0 :(得分:0)
在命令处理程序MyCommandUC执行此操作..
public void MyCommandUC
{
MyProperty = false; // for hidden
}
但是说这个我想告诉你,你的代码很混乱,有时你设置隐藏的可见性有时候你把它设置为Collapsed,你尝试从xaml设置truevalue和FalseValues但你的转换器有硬编码它的构造函数中的值使得从xaml
设置任何东西都没用---编辑
我刚看到这个..而我......!
set {
if (_myProperty== true)
_myProperty= value;
else
_myProperty= true;
OnPropertyChanged("MyProperty");
}
将上述代码更改为
set {
_myProperty= value;
OnPropertyChanged("MyProperty");
}
答案 1 :(得分:0)
单击MenuItem时,MyProperty的值发生变化,我使用ICommand捕获单击。我认为这样做
_private bool _myProperty;
...
set
{ _
myProperty = value;
}
}
public void MyCommandUC()
{
if (MyProperty == false)
MyProperty = true;
else
MyProperty = false;
}
但不能工作