Получает доступ к тексту текстового блока внутри ButtonStyle из кода - PullRequest
0 голосов
/ 15 марта 2012

Как получить доступ к свойству tbRegistrationBtn.text из кода из пользовательского стиля?

Моя кнопка создается динамически из codebehind и добавляется в родительский элемент управления (панель стека): Кнопка создается, когда я нажимаю другую кнопку на моем экране.

Codebehind:

                Button newBtn = new Button();
                newBtn.Width = 160;
                newBtn.Height = 46;
                newBtn.Style = this.FindResource("ButtonStyleRegistration") as Style;
                spHorizontal.Children.Add(newBtn);

Xaml:

        <Style x:Key="ButtonStyleRegistration" TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid x:Name="registrationButton">
                        <Rectangle Fill="#FF89959A" Height="Auto" RadiusY="15" RadiusX="15" Stroke="White" Width="Auto"/>
                        <TextBlock x:Name="tbRegistrationBtn" TextWrapping="Wrap" Text="" HorizontalAlignment="Center" Margin="7.5,14.973,0,16.84" d:LayoutOverrides="Height"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsFocused" Value="True"/>
                        <Trigger Property="IsDefaulted" Value="True"/>
                        <Trigger Property="IsMouseOver" Value="True"/>
                        <Trigger Property="IsPressed" Value="True"/>
                        <Trigger Property="IsEnabled" Value="False"/>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="FontSize" Value="10.667"/>
    </Style> 

Любая попытка получить текстовый блок приводит к нулевой ошибке. Попытка:

            Style style = this.FindResource("ButtonStyleRegistration") as Style;
            newBtn.Style = style;
            TextBlock tb = (TextBlock)style.Resources.FindName("tbRegistrationBtn");
            tb.Text = "test";

С уважением.

Ответы [ 2 ]

0 голосов
/ 15 марта 2012

Ответ max определенно подходит для вашей ситуации.Однако, почему бы не сделать это:

<TextBlock TextWrapping="Wrap" Text="{TemplateBinding Content}"
           HorizontalAlignment="Center" Margin="7.5,14.973,0,16.84"/>

, чем вы можете установить newBtn.Content = "test" в коде позади.

0 голосов
/ 15 марта 2012

Вы можете использовать VisualTreeHelper для навигации по визуальному дереву вашей кнопки. Используйте эту вспомогательную функцию:

public static T FindVisualChild<T>(DependencyObject obj, string name)
    where T : DependencyObject
{
    var count = VisualTreeHelper.GetChildrenCount(obj);
    for(int i = 0; i < count; i++)
    {
        var child = VisualTreeHelper.GetChild(obj, i);

        if(child != null)
        {
            var res = child as T;
            if(res != null && (string)res.GetValue(FrameworkElement.NameProperty) == name)
            {
                return res;
            }
            res = FindVisualChild<T>(child, name);
            if(res != null) return res;
        }
    }

    return null;
}

Также вам нужно заставить свою кнопку построить свое визуальное дерево на основе шаблона (потому что оно задерживается по умолчанию):

newBtn.ApplyTemplate();

И, наконец, установите TextBlock текст:

var tb = FindVisualChild<TextBlock>(newBtn, "tbRegistrationBtn");
tb.Text = "Registration";
...