0

I am fairly new to WPF and have two questions?

Question #1: From my XAML snip below, by button "btnRed" word's fine with my code behind. When the button is clicked, the proper view is display. However, how does one perform the same thing "programmatically"? Hence, my next question.

Question #2: I am not sure how to make a "textbox" and "button" work together to perform the same action. What I'm trying to do is this. (1) I would like the textbox to be linked to the "DataContext" of the button, "btnDisplayView". (2) so when I type in, say, "RedView" into the textbox and click the button, the correct view is displayed.

My long term goal is to have a database, with a couple of tables. A table for "MenuItems" and a table for "Views". Instead of using buttons, I'll use the menu control. Then once a menu item is selected, it would display the correct view.

But for now, I'm startings small and trying to keep it simple:

--------- WPF - XAML START ---------------------------

<StackPanel Grid.Column="0" Orientation="Vertical">
    <TextBox x:Name="txtDisplayView" Height="23" Margin="5" TextAlignment="Center"/>
    <Button x:Name="btnDisplayView" Content="Display" Margin="5" Click="btnDisplay_Click"/>

    <Button x:Name="btnRed" Content="Red" Margin="5" DataContext="RedView" Click="Red_Click"/>
</StackPanel>

<StackPanel Grid.Column="1" Orientation="Vertical">
    <ContentControl Margin="5" Content="{Binding}"/>
</StackPanel>

-----------WPF - XAML END -------------------------

If someone could show me how to get this to work, it would help me move my project in the right direction and would be greatly appreciated.

1 Answer 1

1

What you need here is:

  1. Create a property in your DataContext that represents the selected item
  2. Bind that property to your TextBox element

Now, you have two options. One is "WPF Friendly" and the other is more Windows Forms-ish:

  1. Create a command (take a look at this article) that reads a parameter, which will be binded to the property you created before
  2. On the Click event, you can read the binded property value

I personally prefer the first solution. Why? Because when you change it to a Menu, for example, your work will be only to populate the menu with your list items (the MenuItem class also has a Command property, so the implementation is the same as with a Button). You will only need to change the source!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.