Search code examples
c#wpfdata-binding

Binding directly to an object property


I'm still getting the hang of WPF and data binding is painful. I want this textbox to bind to the Name property of the page's Exam object.

The following is how I'm usually doing it.

        <StackPanel VerticalAlignment="Center" x:Name="CreateExamStackPanel">
            <TextBox Style="{StaticResource placeHolder}" Tag="Exam Name" 
                     x:Name="NameTextBox" Text="{Binding Path=Name}" />
        </StackPanel>
    public partial class CreateExam : Page {
        public CreateExam() {
            InitializeComponent();
            CreateExamStackPanel.DataContext = Exam;
        }

        private void CreateButton_Click(object sender, RoutedEventArgs e) {
            if (Exam.Name?.Length > 0)
                MessageBox.Show($"Exam named: {Exam.Name}");
            else
                MessageBox.Show($"Please enter a name for the exam.");
        }

        public Exam Exam { get; set; } = new Exam();
    }

But it seems to me that there "should" be a way to bind to the Exam entirely through the XAML. The {Binding Path=Name} points to the property of the Exam, but is there a way to point directly to the Exam itself?

I've tried adding {Binding Exam} to both the StackPanel and the TextBox in the XAML (and removing the .DataContext = Exam from the C# but that doesn't seem to work.


Solution

  • I think You need the entire properties in the CreateExam to the Page right?

    If that's the case you can do like

    public CreateExam()
     {
        InitializeComponent();
         this.DataContext = this;
     }
    

    In your XAML you can bind like

         <StackPanel VerticalAlignment="Center" x:Name="CreateExamStackPanel">
            <TextBox Style="{StaticResource placeHolder}" Tag="Exam Name" 
                     x:Name="NameTextBox" Text="{Binding Path=Exam.Name}" />
        </StackPanel>
    

    or If you need whole Exam as DataContext in your Page then

    public CreateExam()
     {
        InitializeComponent();
         this.DataContext = Exam;
     }
    

    then your XAML looks like

     <StackPanel VerticalAlignment="Center" x:Name="CreateExamStackPanel">
        <TextBox Style="{StaticResource placeHolder}" Tag="Exam Name" 
                 x:Name="NameTextBox" Text="{Binding Path=Name}" />
    </StackPanel>
    

    Let me know which one is the case you need so I can remove the other one.