MouseEnter event: how to show data of one control into another? - c#

I Use Visual Studio, C# and WPF. I create a main window called "WindowsMonopoly" and an user control called "CasellaColore", with some properties. In the "WindowMonopoly" I put more of the "CasellaColore". I have this situation:
<Monopoly:CasellaColore x:Name="Casella8" Grid.Row="10" Grid.Column="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Indice="8" ColoreCasella="Black"/>
<Monopoly:CasellaColore x:Name="Casella9" Grid.Row="10" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Indice="9" ColoreCasella="Black"/>
etc...
Now I want that when I put my cursor on one of the "CasellaColore", this must be showed into a grid. Explaining with simple language:
When the cursor is on the "CasellaColore", then show this "CasellaColore" into a grid into the "WindowMonopoly".
I must redo "all" the Monopoly, for as a school's exercise. My knowledge of C# and WPF is limited, but I'm one of the best of my class in programming.

Related

WPF C# Button Binding and TextBox to Button Binding

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.
What you need here is:
Create a property in your DataContext that represents the selected item
Bind that property to your TextBox element
Now, you have two options. One is "WPF Friendly" and the other is more Windows Forms-ish:
Create a command (take a look at this article) that reads a parameter, which will be binded to the property you created before
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!

Boardgame with dynamically created grid and a control inside to use drag and drop

For school I have to create a boardgame of my choice. I chose a simple boardgame where you have to combine blocks of different colors in a way to gain most points out of it. You can have 2 to 4 players.
Until now I build a WPF application with MVVM and PRISM. The user is pressing a button to decide the amount of players and based on that I want to create a grid dynamically in XAML (because of MVVM and no code-behind) with sizes of 6x6, 7x7 and 8x8. In each cell there need to be a control (I don't know which one) which can hold a visual block.
My idea is to create that grid, put a ListBox in each cell, allow just one item for the ListBox and drag and drop a Rectangle on it.
For the dynamically created grid I read about using ItemsControl to build it up. Here a short code example, which isn't working:
<ItemsControl Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Path=GameBoard}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid ShowGridLines="True" Row="{Binding Path=Rows}" Column="{Binding Path=Columns}">
<Grid.RowDefinitions>
<RowDefinition MinHeight="20"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="20"/>
</Grid.ColumnDefinitions>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Inside I could place a ListBox to hold that block I was talking about. For my understanding I need to have a property bound to every single cell/ListBox to actually hold it and work with it in code.
There is plenty of stuff on the internet, but I couldn't wire it together to get it working. Do you have a point to start for me?

How do I tab between text boxes on a form in C#?

I'm trying to get the functionality to tab to the next text box once the user has input their data for the previous text box. For example, once they filled in a company name I'd like to be able to hit Tab and set the focus on the next text box "Job Name". Is this done in the code or the form properties?
Here is some of my code. I'm unsure how to nest a KeyEventsArgs within these, which is how I've seen others set the focus to the next text boxes using the KeyPress function.
private void textBox1_TextChanged(object sender, EventArgs e)
{
CompanyName = textBox1.Text;
textBox1.AcceptsTab = true;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
JobName = textBox2.Text;
textBox2.AcceptsTab = true;
}
From the question you've asked and the code sample provided, there seems to be somewhat of a disconnect between your approach and the desired functionality.
As you would like the user to be able to use the Tab key in order to shift keyboard focus between elements in the window, you need only provide a TabIndex attribute on each of your TextBox controls. There is no need to use the TextChanged events to achieve this and it can be done completely in XAML for simplicity's sake.
From how I interpret your question, your next follow-on will likely be:
How do I initially give focus to a control when the application
starts?
To address this, there are a couple of alternatives available, simplest of which comes in the form of the FocusManager, which again I've illustrated usage of in XAML.
For convenience, here is a XAML-only implementation with TabIndex and FocusManager implemented:
<Window x:Class="tab_navigation.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:tab_navigation"
mc:Ignorable="d"
Title="MainWindow" ResizeMode="NoResize" SizeToContent="WidthAndHeight" FocusManager.FocusedElement="{Binding ElementName=TbxCompanyName}">
<Grid Margin="10">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Vertical" Margin="0,0,0,10">
<Label Content="Company Name:" Target="{Binding ElementName=TbxCompanyName}" />
<TextBox Name="TbxCompanyName" TabIndex="0" Width="160" HorizontalAlignment="Left"/>
</StackPanel>
<StackPanel Orientation="Vertical">
<Label Content="Job Description:" Target="{Binding ElementName=TbxJobDescription}"/>
<TextBox Name="TbxJobDescription" TabIndex="1" Width="160" HorizontalAlignment="Left"/>
</StackPanel>
</StackPanel>
</Grid>
Give me a shout if you need any further help, although I would strongly recommend checking out some of the MSDN resources first, particularly those concerning Focus
UPDATE: In response to comment regarding implementing the solution,
WPF has a different design and best practices from that of WinForms.
I would strongly make the case that you cease using Forms and instead use a Window or UserControl derived class in place of a Form in your WPF project unless there is a very, very good reason for doing so. If you continue to use a Form inside of your WPF project, you will indeed need to implement your own keyboard navigation logic inside that form, and bridge various other gaps you'll inevitably run into when trying to get a Form behave in a commonly acceptable way.
I'll instead show you how you can achieve your request using an objectively better and more suitable approach in WPF-only, using Window or UserControl elements. There is also a complete solution zip downloadable here.
WPF is by design a lot more modular than WinForms and splits the areas of concerns nicely by default, although most developers implement a design pattern ontop of this; MVVM is the current darling of WPF, and does add quite a lot of value to a project, although it is outside the scope of your question, so I shall instead address the question itself on the grounds of how to achieve the request in its most basic forms. Do please be aware though that this is not the entirely ideal solution and I would strongly recommend you learn and implement the MVVM pattern for WPF if you are not already familiar with it.
With that disclaimer out of the way, instead of using a Form in WPF, its more useful for us to make a class which derives from Window. An even more common scenario in WPF would be that you would want to have a single window whose content changes between different views, rather than say creating multiple windows, although again that is outside the scope of the question and would rely upon reading into Binding and MVVM. I'm going to be showing you a quick and easy way to get the functionality you've asked for, I'm just trying to iterate here that this is not the norm almost all of the time.
To make a working solution, do the following to your project:
Right click your project in the solution explorer (presuming you are using Visual Studio)
'Add' a 'New Item...'.
Choose the 'Window (WPF)' template and name it. I'm going to call it CustomerInformationEntry from here out.
Open the CustomerInformationEntry.xaml file that has been created for us, remove the <Grid></Grid> tags and copy/paste this excerpt from the XAML I've already provided from above in their place:
<Grid Margin="10">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Vertical" Margin="0,0,0,10">
<Label Content="Company Name:" Target="{Binding ElementName=TbxCompanyName}" />
<TextBox Name="TbxCompanyName" TabIndex="0" Width="160" HorizontalAlignment="Left"/>
</StackPanel>
<StackPanel Orientation="Vertical">
<Label Content="Job Description:" Target="{Binding ElementName=TbxJobDescription}"/>
<TextBox Name="TbxJobDescription" TabIndex="1" Width="160" HorizontalAlignment="Left"/>
</StackPanel>
</StackPanel>
</Grid>
Add FocusManager.FocusedElement="{Binding ElementName=TbxCompanyName} to the Window element in CustomerInformationEntry.xaml.
This is our view or visual representation finished with now, and all that remains is to instanciate a new CustomerInformationEntry from our other Window or UserControl, and to then display it. In this case I'm going to be putting a button onto the MainWindow.xaml, and providing it a click event which will create the instance of our new Window:
In MainWindow.xaml add <Button Name="BtnOpenCustomerInformationEntry" Content="Enter Customer Information" Click="OpenCustomerInformationEntry"/>. In my case I'll be adding the button inside my object, although you can put it wherever you like if you've already created your initial window.
In MainWindow.xaml.cs we'll add a new private method which will be used by the Click event of your new button. Adding the following code:
private void OpenCustomerInformationEntry(object sender, RoutedEventArgs e)
{
CustomerInformationEntry myWindow = new CustomerInformationEntry();
myWindow.Show();
}
That's it, you now have a button in your MainWindow.xaml which when clicked uses the OpenCustomerInformationEntry method defined in MainWindow.xaml.cs, which in turn makes an instance of your CustomerInformationEntry window and displays it.
If you would still rather stick with the Forms approach, you can do that by using WindowsFormsHost, usage of which is discussed here.
Best Regards,
JC

Focus on Canvas overlapping the listbox in WP7

I have a situation here. I have a page containing a ListBox. The ListBox is populated with Items if it is able to fetch the data from a web service. Now when the user doesn't have network connectivity on his phone or the webservice doesn't respond back with Ok status, I want to show the user a pop-up with an option to Retry or select Ok to stay on the same page (though it sounds dumb). Now for this I used a Canvas:
<Canvas Name="Nonetwork" Height="150" Width="280" HorizontalAlignment="Center" VerticalAlignment="Center" Background="DodgerBlue" Visibility="Collapsed" Margin="111,160,92,160" >
<TextBlock VerticalAlignment="Top" Height="120" Width="280" Text="No Network is currently availabe" TextAlignment="Center" TextWrapping="Wrap" Foreground="White" FontSize="28" />
<Button Margin="30, 80" Height="60" Width="100" Content="OK" FontSize="18" Click="Ok_Click"/>
<Button Margin="150, 80" Height="60" Width="100" Content="Retry" FontSize="18" Click="Retry_Click"/>
</Canvas>
Well as most of you experienced guys would have guessed, the canvas is buried inside the listbox and is not accessible when there is no network connectivity. So I have a blank page with the canvas but the user is not able to click on Ok or Retry. Please help
Please do let me know if there is any other approach to solve this problem. I tried Popup but I cant Navigate to the main page from a pop-up since that is a user control page. Any help is higly appreciated
Well, I placed my Canvas below the ListBox and the problem was solved. I didn't know that positioning of the controls in the XAML would have so much effect ...
The order in which elements are rendered in Silverlight is determined firstly by where they appear in the visual object hierarchy and secondly by their ZIndex property.
The Canvas has a third attached property named ZIndex that you can use to override the default layering of elements. Although this Canvas.ZIndex attached property is defined by the Canvas class, it actually works with any type of panel.
You can also try Canvas.ZIndex property:
Canvas.ZIndex Attached Property
What you do is a wrong practice and not at all recommended.
ChildWindow is the class you should use to display such kind of dialog.
Using a Popup is also another approach you can use.
NOTE: I know the simplest approach would be to use MessageBox.Show(), but it would create a popup out of silverlight frame and does not allow theming/styling and other customizations.

WPF Design question

Lets say i am developing a chat, first you come to a login window and when your logged in i want to use the same window but chaning the control :P how would be the best way to desight this?
is there any good way to implement this what root element should i use?
Thanks a lot!!
Take a look at Josh Smith's article in MSDN magazine (http://msdn.microsoft.com/en-us/magazine/dd419663.aspx). He describes an interesting method where you have a content presenter on your main window use data templates to switch out what the window is showing.
If you want to do this all within the same window, you could use a Grid as the root element and host a login element (possibly another grid for layout) and the chat window. These elements would stack on top of one another, depending upon the order in which you declare them. To hide the chat element initially, set its Visibility to Collapsed
You could then have the login element's Visibility set to Collapsed when the user submits their login details, and have the chat element's Visibility set to Visible.
I did something similar once and it worked well for me.
Hope that helps.
EDIT I knocked this together in Kaxaml for you to play with (and because I like playing with XAML):
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Border x:Name="_loginForm" BorderBrush="#888" BorderThickness="3" CornerRadius="5"
HorizontalAlignment="Center" VerticalAlignment="Center" Padding="10" Visibility="Visible">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" Height="30">Welcome to chat</TextBlock>
<TextBlock Grid.Row="1" Grid.Column="0">User Name</TextBlock>
<TextBox Grid.Row="1" Grid.Column="1" x:Name="_userName" />
<TextBlock Grid.Row="2" Grid.Column="0">Password</TextBlock>
<TextBox Grid.Row="2" Grid.Column="1" x:Name="_password"></TextBox>
<Button Grid.Row="3" Grid.Column="1">Log In</Button>
</Grid>
</Border>
<DockPanel x:Name="_chatForm" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" LastChildFill="True" Visibility="Collapsed">
<DockPanel DockPanel.Dock="Bottom" LastChildFill="True" Height="70">
<Button DockPanel.Dock="Right" Width="70">_Send</Button>
<TextBox x:Name="_input" HorizontalAlignment="Stretch">Hello world</TextBox>
</DockPanel>
<ListBox x:Name="_messageHistory" />
</DockPanel>
</Grid>
</Page>
Initially the element _loginForm is visible. You'd attach a handler for the Log In button's Click event that would hide it, and show the _chatForm instead.
This example shows usage of several layout controls -- the Grid, DockPanel and StackPanel.
Alternatively, you can use a StackPanel for your layout. As a simple example, you can have 2 elements in your panel; a custom login control as well as the chat 'display' control. After successfully logging in, remove the custom login control from your stack so only the chat is visible.
It's WPF! Animate them in and out of view...you can do that now. There's a collaborative project on Google Code called Witty (a desktop Twitter client written in WPF), and they do something really cool that you might want to borrow from. Come to think of it, there's another WPF Twitter client (blu) that does similar animations that you might want to look at.
In Witty, the Settings dialog is a normal window, but when you switch between the tabs, a storyboard slides the part of the window you requested into view. I haven't debugged the app at this level, but I'm assuming that they have a horizontal StackPanel populated with containers that are fixed to the height and width of the dialog, and they slide them in and out with a storyboard.
Take a look at both of these apps for ideas. You may want to do something similar, but being that this is a WPF app, the sky is really the limit.
Witty
blu
There are already some answers here on, how to swap two elements at the view level. This post offers a way to more fundamentally create a modular application design with interchangeable views.
You could take a look at the Composite Application Library. It is a small library (developed by Microsoft) that among other things aid in making your application more modular. With this you can define regions of your GUI, that can have interchangeable views.
In your containing xaml import the CAL namespace and use RegionManager to define a region:
<Window ...
xmlns:cal="http://www.codeplex.com/CompositeWPF"
...>
...
<ItemsControl cal:RegionManager.RegionName="MyRegion" />
...
Then you can swap views in this region, preferably in a module:
_regionManager.Regions["MyRegion"].Add(new LoginView());
...swap...
_regionManager.Regions["MyRegion"].Add(new ChatView());
This is of course just an outline of what you can do. In order to implement this solution, you will have to look further in to CAL. It has great documentation and lots of examples to learn from.
I think a more intuitive solution is to use a Frame control as the base control of your window - and to use the NavigateService to change the source of the Frame to different Page controls (which could be defined in separate assemblies, or in your same project as different XAML files).
Your Window:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Frame Source="LogonPage.xaml" NavigationUIVisibility="Hidden" />
</Window>
And your separate LogonPage:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Logon">
<!-- Your content of the page goes here... -->
</Page>

Categories