0

I created a simple User Control and used it in the xaml file (mainWindow.xaml).

I named the instance VolumeMeter of the user control and then tried to use it in function in the cs file (mainWindow.cs) but the name is not recognized

The name doesn't exist in the current context

Why is that and what can I do to fix it?

xaml:

<Window x:Class="testUserControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:MyNameSpace="clr-namespace:testUserControl.UserControls"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Button Name="btnShow" Content="Show"></Button>
        <StackPanel Name="stkTest" Grid.Row="1" Orientation="Vertical">
            <MyNameSpace:UserControl1 Name="VolumeMeter"></MyNameSpace:UserControl1>
        </StackPanel>
    </Grid>
</Window>

cs file:

namespace testUserControl
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnShow_Click_1(object sender, RoutedEventArgs e)
        {
             VolumeMeter.Enable = false;//Compile error
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Amit Lipman
  • 687
  • 7
  • 19

3 Answers3

3

Try using x:Name instead of Name [msdn]:

...
<StackPanel Name="stkTest" Grid.Row="1" Orientation="Vertical">
   <MyNameSpace:UserControl1 x:Name="VolumeMeter"></MyNameSpace:UserControl1>
</StackPanel>
...
kmatyaszek
  • 19,016
  • 9
  • 60
  • 65
1

Using x:Name would work. Please refer In WPF, what are the differences between the x:Name and Name attributes? for a very good explanation.

Community
  • 1
  • 1
  • 1
    That would be another error: ...does not contain a definition for 'Enable' and no extension method 'Enable' accepting a first argument of type could be found (are you missing a using directive or an assembly reference?) – Bizhan Feb 15 '15 at 17:18
0

You should use the x:Name rather than Name see this post to see the difference In WPF, what are the differences between the x:Name and Name attributes?

Community
  • 1
  • 1
Benzara Tahar
  • 2,058
  • 1
  • 17
  • 21