Как динамически связать stati c DependencyProperty, определенный в классе, со свойством в другом классе xaml? - PullRequest
0 голосов
/ 08 апреля 2020

У меня есть состояние c DependencProperty IsControlVisibleProperty в MyControl.xaml.cs. И его значение изменяется внутри того же класса. И я хочу слушать это свойство в другом свойстве видимости элемента управления всякий раз, когда значение IsControlVisibleProperty изменяется.

MyControl.xaml.cs:

public partial class MyControl : UserControl
{
    public static DependencyProperty IsControlVisibleProperty = DependencyProperty.Register(nameof(IsControlVisible), typeof(bool), typeof(MyControl));
    public bool IsControlVisible
    {
        get{ return (bool)GetValue(IsControlVisibleProperty); }
        set { SetValue(IsControlVisibleProperty, value); }
    }

    // In a function I am updating the dependency property
    private void UpdateProp(bool isVisible)
    {
        this.SetValue(UserControl1.IsControlVisible, isVisible);
    } 

Теперь я хочу использовать значение IsControlVisibleProperty в другом файле xaml
SampleControl.xaml :

<UserControl x:Class="SampleControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:converter="http://schemas.microsoft.com/netfx/2007/xaml/presentation"
    Height="300" Width="300">
<UserControl.Resources>
    <converter:BooleanToVisibilityConverter x:Key="boolToVisConverter"/>
</UserControl.Resources>
<Grid>
    <local:MyControl/>
    <TextBlock Name="ErrorMessage" Text="Failed to run" Visibility="{Binding ElementName="ErrorMessage" , Path=(local:MyControl.IsControlVisible), Converter={StaticResource boolToVisConverter}, Mode=TwoWay}"/>

</Grid>

Таким образом, мой TextBlock (ErrorMessage) не связывает IsVisibleProperty из MyControl.xaml.cs. Я хочу, чтобы IsVisibleProperty всегда связывался с TextBlock (где бы ни менялось свойство, оно должно также изменять его видимость), а не один раз при создании. К сожалению, я не могу этого добиться. Есть ли другой способ сделать это?

1 Ответ

0 голосов
/ 09 апреля 2020

Объявление DependencyProperty всегда является stati c, но ваше свойство IsControlVisible не является stati c. Фактически, вы не можете объявить свойство зависимости static, потому что методы GetValue и SetValue не static.

. Вам нужно определить присоединенный Свойство зависимостей в static классе:

public static class MyProperties
{
    public static readonly DependencyProperty IsControlVisibleProperty = DependencyProperty.RegisterAttached(
        "IsControlVisible",
        typeof(bool),
        typeof(MyProperties));

    public static void SetIsControlVisible(UIElement element, Boolean value)
    {
        element.SetValue(IsControlVisibleProperty, value);
    }

    public static bool GetIsControlVisible(UIElement element)
    {
        return (bool)element.GetValue(IsControlVisibleProperty);
    }
}

Затем вы можете установить это свойство для любого UIElement (или любого типа в ваших методах get и set), используя такие методы доступа:

MyProperties.SetIsControlVisible(this, true); //this = the UserControl

Вы связываете с прикрепленным свойством родителя UserControl следующим образом:

<TextBlock Name="ErrorMessage" Text="Failed to run" 
                   Visibility="{Binding Path=(local:MyProperties.IsControlVisible), 
                        Converter={StaticResource boolToVisConverter},
                        RelativeSource={RelativeSource AncestorType=UserControl}}" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...