我在用户控件中有3个按钮,我想显示和隐藏WPF应用程序中的一个按钮或来自用户控件。它不适合我。我已经实现了INotifyPropertChanged
接口来通知View。请检查一下。
<UserControl x:Class="WPFUserControl.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
xmlns:vis="clr-namespace:WPFUserControl"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<vis:BoolToVisibilityConverter x:Key="BoolToVis" ></vis:BoolToVisibilityConverter>
</UserControl.Resources>
<Grid>
<Button Content="Button1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75"/>
<Button Content="Button2" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="106,0,0,0"/>
<Button Content="ShowHide" Visibility="{Binding IsShowHideVisible, Converter={StaticResource BoolToVis}, ConverterParameter=False}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="215,0,0,0"/>
</Grid>
public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
private bool isShowHideVisible;
public bool IsShowHideVisible
{
get { return isShowHideVisible; }
set
{
if(isShowHideVisible!=value)
{
isShowHideVisible = value;
}
}
}
public UserControl1()
{
InitializeComponent();
// IsShowHideVisible = false;
}
private void OnPropertyChange(string pPropertyName)
{
if(PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(pPropertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
答案 0 :(得分:1)
在IsShowHideVisible-Property的setter中,您必须在OnPropertyChanged("IsShowHideVisible")
之后立即致电isShowHideVisible = value;
。
您的财产看起来像是:
public bool IsShowHideVisible
{
get { return isShowHideVisible; }
set
{
if(isShowHideVisible!=value)
{
isShowHideVisible = value;
OnPropertyChanged("IsShowHideVisible");
}
}
}
如果您使用.net 4.5或更高版本,则可以重写OnPropertyChanged
- 方法,如:
private void OnPropertyChange([CallerMemberName]string pPropertyName = null)
{
if(PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(pPropertyName));
}
}
与您的财产相比,您只需拨打OnPropertyChanged();
而不是OnPropertyChanged("IsShowHideVisible");
答案 1 :(得分:0)
在构造函数中添加this.DataContext = this并在set字段中添加OnPropertyChange(“IsShowHideVisible”)后,其工作。
{{1}}