Как получить доступ к другому элементу управления пользовательской кнопки в окне кода - PullRequest
0 голосов
/ 10 марта 2012

Я новичок в WPF.я создаю пользовательскую кнопку в XAML следующим образом

<Button x:Class="WPFApp.ButtonMainMenuCat"
             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" 
             d:DesignHeight="150" d:DesignWidth="177">
    <Button.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <Grid>
                <Image Name="Background" Source="/WPFApp;component/Resources/MainScreenMenuBackground.png" Stretch="Fill" />
                <Image Name="MenuNormal" Source="/WPFApp;component/Resources/Audio_Gray.png" Stretch="Fill" Height="62" Width="56" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                <Image Name="Pressed" Source="/WPFApp;component/Resources/subMenuNormalButton.png" Stretch="Fill" Visibility="Hidden"/>
                <Image Name="Focused" Source="/WPFApp;component/Resources/buttonFocus.png" Margin="7,7,7,7" Visibility="Hidden"  Stretch="Fill"/>

            </Grid>

            <ControlTemplate.Triggers>
                <Trigger Property="IsPressed" Value="True">
                    <Setter TargetName="MenuNormal" Property="Visibility" Value="Hidden"/>
                    <Setter TargetName="Pressed" Property="Visibility" Value="Visible"/>
                </Trigger>
                <Trigger Property="IsFocused" Value="True">
                    <Setter TargetName="MenuNormal" Property="Visibility" Value="Hidden"/>
                    <Setter TargetName="Focused" Property="Visibility" Value="Visible"/>

                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Button.Template>
</Button>

, а код позади выглядит следующим образом

namespace WPFApp
{
    /// <summary>
    /// Interaction logic for ButtonMainMenuCat.xaml
    /// </summary>
    public partial class ButtonMainMenuCat : Button
    {
        public ButtonMainMenuCat()
        {
            InitializeComponent();
        }

        public void SetMenuImage(String MenuName)
        {
            var uriSource=new Uri("");
            switch (MenuName.ToLower())
            {
                case "home":
                   uriSource = new Uri(@"/WPFApp;component/Resources/Home_Gray.png", UriKind.Relative);
                   break;
                case "video":
                    uriSource = new Uri(@"/WPFApp;component/Resources/Vedeo_Gray.png", UriKind.Relative);
                    break;
                case "audio":
                    uriSource = new Uri(@"/WPFApp;component/Resources/Audio_Gray.png", UriKind.Relative);
                    break;
                case "services":
                     uriSource = new Uri(@"/WPFApp;component/Resources/Services_Gray.png", UriKind.Relative);
                    break;
                case "shopping":
                    uriSource = new Uri(@"/WPFApp;component/Resources/Shoppings_Gray.png", UriKind.Relative);
                    break;
                case "channels":
                     uriSource = new Uri(@"/WPFApp;component/Resources/Channels_Gray.png", UriKind.Relative);
                    break;
                default:
                     uriSource = new Uri(@"/WPFApp;component/Resources/Home_Gray.png", UriKind.Relative);
                    break;
            }
            WPFApp.ButtonMainMenuCat.MenuNormal.Source = new BitmapImage(uriSource);

        }
    }
}

Теперь моя проблема заключается в том, что я хочу изменить источник изображения MenuNormal во время выполнения,но это дает мне ошибку, что Error ButtonMainMenuCat 'не содержит определения для' MenuNormal '

Поэтому, пожалуйста, предложите, как я могу получить доступ к элементам управления в коде, который создан в XAML

Ответы [ 2 ]

2 голосов
/ 10 марта 2012

Чтобы получить экземпляр «Image» в вашем коде, вам нужно использовать FrameworkElement.GetTemplateChild

Image menuNormal = (Image)GetTemplateChild("MenuNormal");

В качестве альтернативы вы можете привязать источникэтого изображения к свойству вашей кнопки, это подход, который я бы использовал.

Редактировать: Если вы используете GetTemplateChild, то вы также должны добавить TemplatePartAttribute к вашему классу, этоне требуется, а просто хорошая практика.

1 голос
/ 10 марта 2012

Вам необходимо зарегистрировать Свойство зависимости на элементе управления, унаследованном от Button, а затем привязать источник изображения к этому свойству.

Затем вы можете установить это свойство в коде приложения, чтобы изменить изображение.

Вот введение:

http://www.switchonthecode.com/tutorials/wpf-tutorial-introduction-to-dependency-properties

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...