你好,
阅读了数小时的关于可见性绑定的许多主题后,我在这里问,因为我无法使案例发挥作用。
我有一个带有自定义附加属性的网格(类型为System.Windows.Visibily),我想使用该属性显示(或不显示)网格内的文本块(通过绑定)。我也想每次自定义附加属性更改时更改可见性。
我到目前为止所做的:CustomProperties类:
public static class CustomProperties
{
public static readonly DependencyProperty starVisibilityProperty =
DependencyProperty.RegisterAttached("starVisibility",
typeof(System.Windows.Visibility), typeof(CustomProperties),
new FrameworkPropertyMetadata(null));
public static System.Windows.Visibility GetStarVisibility(UIElement element)
{
if (element == null)
throw new ArgumentNullException("element");
return (System.Windows.Visibility)element.GetValue(starVisibilityProperty);
}
public static void SetStarVisibility(UIElement element, System.Windows.Visibility value)
{
if (element == null)
throw new ArgumentNullException("element");
element.SetValue(starVisibilityProperty, value);
}
}
然后这是我的xaml:
<Grid Name="server1State" Grid.Row="1" local:CustomProperties.StarVisibility="Hidden">
<TextBlock Name="server1Star" Text="" FontFamily="{StaticResource fa-solid}" FontSize="30" Margin="10" Foreground="#375D81" Visibility="{Binding ElementName=server1State, Path=server1State.(local:CustomProperties.starVisibility)}"/>
</Grid>
但是当我运行我的应用程序时,文本块绝对不会被隐藏,这是可见的,并且永远不会改变。我已经尝试使用Path和INotifyPropertyChanged做很多事情,但是当我使用静态自定义附加属性时,我没有设法使其正常工作。
也许你们中有些人可以帮助我,谢谢。
您在Binding.Path
上的TextBlock
错误。
由于我已阅读您的评论,所以您更喜欢使用布尔属性,我将展示如何使用库的bool
将Visibility
值转换为BooleanToVisibilityConverter
枚举值。我认为您可能已经知道了,但是由于您输入的错误BooleanToVisibilityConverter
而感到困惑:
CustomProperties.cs
Binding.Path
MainWindow.xaml
public class CustomProperties : DependencyObject
{
#region IsStarVisibile attached property
public static readonly DependencyProperty IsStarVisibileProperty = DependencyProperty.RegisterAttached(
"IsStarVisibile",
typeof(bool),
typeof(CustomProperties),
new PropertyMetadata(default(bool)));
public static void SetIsStarVisibile(DependencyObject attachingElement, bool value) => attachingElement.SetValue(CustomProperties.IsStarVisibileProperty, value);
public static bool GetIsStarVisibile(DependencyObject attachingElement) => (bool)attachingElement.GetValue(CustomProperties.IsStarVisibileProperty);
#endregion
}