how to set focus to a textbox - wpf

I have a windows with this controls.
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
///elemnts in row 0
<StackPanel Grid.Row="1">
<ToolBar x:Name="Toolbar">
<Label Content="TextPattern" />
<ComboBox></ComboBox>
<Button Command="{Binding ScanCommand}">
<Image Source="/Images/sacn.png"></Image>
</Button>
<Button Command="{Binding FaxCommand}" x:Name="FaxButton" PreviewKeyDown="FaxButton_PreviewKeyDown">
<Image Source="/Images/fax.png"></Image>
</Button>
</ToolBar>
<TextBox Width="{Binding ElementName=Toolbar,Path=ActualWidth}" x:Name="BodyTextBox" Focusable="True" TextWrapping="Wrap" AcceptsReturn="True" Text="{Binding Body}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Row="2" >
<Button Content="Save" Command="{Binding SaveCommand}"></Button>
<Button Content="Cancel" Command="{Binding CancelCommand}"></Button>
</StackPanel>
</Grid>
When i use tab key for get focus, it go to savebutton after press tab of faxbutton. But i want to go to BodyTextbox.
I use PreviewKeyDown for set focus.
private void FaxButton_PreviewKeyDown(object sender, KeyEventArgs e)
{
if(e.Key==Key.Tab)
{
BodyTextBox.Focus();
BodyTextBox.SelectAll();
FocusManager.SetFocusedElement(this, BodyTextBox);
}
}
But don't set Focus.

When you load UserControl or Windowcontrol:
Please write this in the UserCOntrol_Load Event:
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input,
new Action(delegate ()
{
BodyTextBox.Focus(); // Set Logical Focus
Keyboard.Focus(BodyTextBox); // Set Keyboard Focus
}));
it will be automatically focus n also u can write content from keyboard without any tab pressing..
Hope this will work for U..
Thanks,
Praveen

Remove the PreviewKeyDown event and Add KeyboardNavigation.TabNavigation="Continue" in tool bar
<ToolBar x:Name="Toolbar" KeyboardNavigation.TabNavigation="Continue">

Related

When I run wpf project application, combobox is not responding to the mouse click and drop down list is not appearing

I am working on wpf application and I am kinda new.
I have added combobox to the stackpanel where first child is menu and second child combobox.
Look at the code below:
<Grid>
<StackPanel>
<Menu Background="Chocolate" Height="30" VerticalAlignment="Top">
<MenuItem Header="File"></MenuItem>
<MenuItem Header="Edit"></MenuItem>
<MenuItem Header="View"></MenuItem>
<MenuItem Header="Help"></MenuItem>
</Menu>
<ComboBox Width="100" Height="30" Loaded="Cbox_Load" Margin="30" SelectionChanged="Cbox_Changed_event">
</ComboBox>
</StackPanel>
<ScrollViewer>
------rest of controls---
</ScrollViewer>
</Grid>
And the code to load data into combobox and handle selection change is as below:
private void Cbox_Changed_event(object sender, SelectionChangedEventArgs e)
{
// string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
}
private void Cbox_Load(object sender, RoutedEventArgs e)
{
List<string> zoomList = new List<string>();
zoomList.Add("100");
zoomList.Add("200");
zoomList.Add("300");
zoomList.Add("400");
var comboBox = sender as ComboBox;
comboBox.ItemsSource = zoomList;
comboBox.Focusable = true;
}
The problem:When run the project, I am unable to click on the combobox to select a combobox item. The combobox appears as if disabled
Please guide.
There are two controls StackPanel and ScrollViewer in the same cell: row="0", column="0". Put them to different cells.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<Menu Background="Chocolate" Height="30" VerticalAlignment="Top">
<MenuItem Header="File"></MenuItem>
<MenuItem Header="Edit"></MenuItem>
<MenuItem Header="View"></MenuItem>
<MenuItem Header="Help"></MenuItem>
</Menu>
<ComboBox Width="100" Height="30" Loaded="Cbox_Load" Margin="30" SelectionChanged="Cbox_Changed_event">
</ComboBox>
</StackPanel>
<ScrollViewer Grid.Row="1">
<!-- ... -->
</ScrollViewer>
</Grid>

WPF Application with Image on button

I have created a WPF application. In that I need to show image on button . So that where should I store that image on my application and how to set source property of the image ??
Please replay
<Button x:Name="Button1" Width="200" Height="200" Content="Button1" Margin="0,0,0,400">
<Button.Background>
<ImageBrush **ImageSource ="Images/AERO.png"** ></ImageBrush>
</Button.Background>
</Button>
In CS File:( Store image in resources or any folder in Project Directory)
private void Button1_Click_1(object sender, RoutedEventArgs e)
{
var brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri("Images/AERO.png"));
Button1.Background = brush;
}
Add a image to your project.
Set this image's property : 'no copy' and 'Resource'
Add a Button,remove it's default 'Content' property.
Add a Image control as this Button's content.
<Grid>
<Button x:Name="button" HorizontalAlignment="Left" Margin="190,136,0,0" VerticalAlignment="Top" Width="104" Height="42">
<Image Source="pen.png" />
</Button>
</Grid>
You can add image on a button like,
<Button>
<StackPanel>
<Image Source="Images/imageName.png" />
</StackPanel>
</Button>
Or else you can try,
<Window.Resources>
<ImageBrush x:Key="MyResource" ImageSource="Images/imageName.png" />
</Window.Resources>
<Grid>
<Button Background="{StaticResource MyResource}"/>
</Grid>
Else try this.
<Window.Resources>
<ImageBrush x:Key="MyResource" ImageSource="Images/imageName.png" />
</Window.Resources>
<Grid>
<Button>
<Button.Content>
<TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="34" Height="19" Margin="0">
<TextBlock.Background>
<StaticResource ResourceKey="MyResource"/>
</TextBlock.Background>
</TextBlock>
</Button.Content>
</Button>
</Grid>
Add image to project and set the image properties:
Build Action: Resource
Copy to Output Directory: Do not copy
Then in the .xaml file add a Button (for example):
<Button HorizontalAlignment="Center" Margin="0" VerticalAlignment="Center" Width="40" Height="40">
<Image Source="Resources/yourImageName.png" Margin="0" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Button>

WPF : ListBox.ItemTemplate doesn't react when click on text or image wpf xaml

I'm new to Xaml and WPF . I'm using the following code to extract botton title and image from RSS feeds .
The problem that the botton react only when user click on the border ... it dosen't react when user click on text or image .
<ListBox.ItemTemplate >
<DataTemplate >
<Button Background="{Binding C:AccentColors}" Width="400" Height="100" HorizontalAlignment="Left" >
<Grid Width="400" Height="100" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Image Source="{Binding XPath=enclosure/#url}" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Top" />
<TextBlock TextWrapping="Wrap" Text="{Binding XPath=title}" FontWeight="Bold" Grid.Column="2"/>
</Grid>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You have to add the Click event in your button.
<Button Background="{Binding C:AccentColors}" Width="400" Height="100" HorizontalAlignment="Left" Click="MethodNameHere".....
and also you have to create and implement the method in the Window C# file
The common mistake is that somebody placed TextBlock on top of button without realizig it, because TextBlock has transparent Background.
Visually, the Text of TextBlock may be outside Button, but since TextBlock alignment is set to strech by default, it fills entire area.
hard to say if this is your case...
<Grid>
<Button Content="I'm not working" Margin="0,100,0,0" />
<TextBlock Text="I'm in top left corner" />
<Grid />
if you set TextBlock.Background to Red, you entire grid would be red.
The button is taking the clicks. You need a handler, either a command binding or if you're not using MVVM - a code behind method:
<Button Click="ButtonBase_OnClick"
Handler will look like this:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
}

Trigger Silverlight button mouseover event for two buttons simultaneously

I have two sets of buttons in two wrappanles that are related to each other. When I move the mouse over a button in one wrappanel, I want its related button to light up at the same time i.e. firing both buttons' mouseover events. So in my code exampes, I when moving over button with label "1.Block", it and its matching button in the other row, "1.Sqaure", must both display their mouseover styles/animations.
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="60" />
<RowDefinition Height="60" />
</Grid.RowDefinitions>
<toolkit:WrapPanel Grid.Column="0" Grid.Row="0">
<Button Content="1. Block" Width="100" />
<Button Content="2. Block" Width="100" />
<Button Content="3. Block" Width="100" />
<Button Content="4. Block" Width="100" />
<Button Content="5. Block" Width="100" />
<Button Content="6. Block" Width="100" />
<Button Content="7. Block" Width="100" />
<Button Content="8. Block" Width="100" />
</toolkit:WrapPanel>
<toolkit:WrapPanel Grid.Column="0" Grid.Row="1">
<Button Content="1. Square" Width="100" />
<Button Content="2. Square" Width="100" />
<Button Content="3. Square" Width="100" />
<Button Content="4. Square" Width="100" />
<Button Content="5. Square" Width="100" />
<Button Content="6. Square" Width="100" />
<Button Content="7. Square" Width="100" />
<Button Content="8. Square" Width="100" />
</toolkit:WrapPanel>
</Grid>
I have no idea where to start on this? Trigger perhaps? Any suggestions will be appreciated.
I think the easiest way to do this is to use VisualStateManager. Following example may be a little rough but should be sufficient overall.
So what we need is to link MouseEnter and MouseLeave events for each pair of buttons in two lists. I don`t have WrapPanel so I used StackPanels instead, but this should not matter if we can get all child buttons from them. Say we have this:
<StackPanel x:Name="LayoutRoot" Orientation="Horizontal">
<StackPanel Name="panel1">
<Button Content="1. Block" Width="100" />
<Button Content="2. Block" Width="100" />
</StackPanel>
<StackPanel Name="panel2">
<Button Content="1. Square" Width="100" />
<Button Content="2. Square" Width="100" />
</StackPanel>
</StackPanel>
Using panels by name we take all their children (this can be done in constuctor for example) and iterate through them assigning same event handlers that move both buttons to required state:
var panel1Buttons = panel1.Children.OfType<Button>().ToList();
var panel2Buttons = panel2.Children.OfType<Button>().ToList();
for (int i = 0; i < panel1Buttons.Count(); i++)
{
var button1 = panel1Buttons[i];
var button2 = panel2Buttons[i];
//assign same mouse enter event handler
MouseEventHandler enterHandler = (s, e) =>
{
VisualStateManager.GoToState(button1, "MouseOver", true);
VisualStateManager.GoToState(button2, "MouseOver", true);
};
button1.MouseEnter += enterHandler;
button2.MouseEnter += enterHandler;
//assign same mouse leave handler
MouseEventHandler leaveHandler = (s, e) =>
{
VisualStateManager.GoToState(button1, "Normal", true);
VisualStateManager.GoToState(button2, "Normal", true);
};
button1.MouseLeave += leaveHandler;
button2.MouseLeave += leaveHandler;
}
So now when mouse enters any of paired buttons they both go to MouseOver state and return to Normal on when mouse leaves.
This us purely UI related functionality so even if you follow MVVM it`s ok to place this in code behind.

Silverlight/WP7: .NET calls the wrong event

I'm developping a Windows Phone 7 app with the Pivot template. This app has a menu toolbar (at the bottom of course).
When I click on the search button (MenusButtonsApplication_Click event to go to the "One" tab), a search page with a ListBox containing some elements is displayed. When I click on one of these elements (ListBoxFoobarSelectionChanged event), I get redirected to another page to show me some details. I use this method.
To go back to the search page again, I must click twice on the search button (MenusButtonsApplication_Click event). Which is not normal.
After a debug, I found that the first click is related to the ListBoxFoobarSelectionChanged while calling the MenusButtonsApplication_Click.
This is the XAML code:
<phone:PhoneApplicationPage
x:Class="Test.Soft.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="clr-namespace:Phone.Controls.Samples;assembly=Phone.Controls.Samples"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"
shell:SystemTray.IsVisible="True"
mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480">
<!--Ressources application-->
<phone:PhoneApplicationPage.FontFamily>
<StaticResource ResourceKey="PhoneFontFamilyNormal"/>
</phone:PhoneApplicationPage.FontFamily>
<phone:PhoneApplicationPage.FontSize>
<StaticResource ResourceKey="PhoneFontSizeNormal"/>
</phone:PhoneApplicationPage.FontSize>
<phone:PhoneApplicationPage.Foreground>
<StaticResource ResourceKey="PhoneForegroundBrush"/>
</phone:PhoneApplicationPage.Foreground>
<Grid x:Name="LayoutRoot" Background="Transparent">
<controls:PivotControl x:Name="pvPrincipal" SelectedIndex="0" TitleTemplate="{StaticResource titleTemplate}" HorizontalAlignment="Left" Width="480" FontSize="22" DefaultItemWidth="480" FontStretch="Normal" Height="697" VerticalAlignment="Top" Margin="0,27,0,0" HorizontalContentAlignment="Left" IsEnabled="True" Visibility="Visible">
<!-- Recherche de comptes -->
<controls:PivotItem Name="pivotOne" Header="One" Loaded="PivotOne_Loaded">
<Grid Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="192*" />
<RowDefinition Height="423*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<ListBox Name="lbSearch" Width="462" Height="377" HorizontalAlignment="Left" BorderThickness="1"
VerticalAlignment="Bottom" SelectionChanged="ListBoxCompteSelectionChanged" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Padding="25,0,0,10" Text="{Binding FoobarCode}" Width="80" HorizontalAlignment="Right" />
<TextBlock Text="- " />
<TextBlock Text="{Binding FoobarDescription}" Padding="5,3,5,5" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</controls:PivotItem>
<!-- Details -->
<controls:PivotItem x:Name="pivotDetails" Header="Details" >
<Grid Name="grDetail" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="398*" />
<RowDefinition Height="167*" />
</Grid.RowDefinitions>
<ListBox>
<StackPanel Margin="5,0,12,20" Grid.ColumnSpan="2">
<TextBlock FontSize="26" FontWeight="Bold"
FontStyle="Normal" Foreground="White" HorizontalAlignment="Left">Détail d'un compte</TextBlock>
</StackPanel>
<StackPanel Grid.Row="1" >
<TextBlock Text="{Binding Path= FoobarCode}" Name="tbCode" HorizontalAlignment="Left" FontWeight="Bold"/>
<TextBlock Text="{Binding Path= Description}" Name="tbDescription" FontWeight="Bold" HorizontalAlignment="Left" />
</StackPanel>
<StackPanel Grid.Row="2" >
</StackPanel>
</ListBox>
</Grid>
</controls:PivotItem>
</Grid>
<!-- ApplicationBar-->
<phone:PhoneApplicationPage.ApplicationBar >
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton x:Name="btnToPivotOne" IconUri="/Icons/appbar.plan.rest.png" Text="One" Click="MenusButtonsApplication_Click"></shell:ApplicationBarIconButton>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem x:Name="menuToPivotOne" Text="To pivot One" Click="MenusButtonsApplication_Click"></shell:ApplicationBarMenuItem>
</shell:ApplicationBarMenuItem>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>
</phone:PhoneApplicationPage>
This interface has:
A pivot (pcPrincipal) containing two tabs (One and Details)
An application bottom bar
For the two buggy functions, here they are:
private void ListBoxFoobarSelectionChanged(object sender, SelectionChangedEventArgs e)
{
grDetail.DataContext = lbSearch.SelectedItem;
lblDescriptionType.Text = mainVM.RetourneDescriptionTypeEncours();
pvPrincipalSelectedItem = pivotDetail;
}
private void MenusButtonsApplication_Click(object sender, EventArgs e)
{
if (sender is ApplicationBarIconButton)
{
switch ((sender as ApplicationBarIconButton).Text)
{
case "One":
// Affichage pivot plan
pvAccueil.Dispatcher.BeginInvoke(() =>
{
pvPrincipal.SelectedItem = pivotOne;
});
break;
default:
break;
}
}
else
{
if (sender is ApplicationBarMenuItem)
{
switch ((sender as ApplicationBarMenuItem).Text)
{
case "To pivot One":
pvAccueil.Dispatcher.BeginInvoke(() =>
{
pvPrincipal.SelectedItem = pivotOne;
});
break;
default:
break;
}
}
}
}
Is it a .NET bug? How can I resolve it? May be should I fire it manually?
Thank you.
It sounds like the button you are using to navigtate back is in the listbox so the first time you "click" it you are actually just selecting the item in the list and the second "click" actually triggers the navigation.
If this is the case, the solution is to move the "Back/search" button outside of hte listbox.
Alternatively, have the navigation take place in the handler for the SelectionChanged event.
Edit.
What is Phone.Controls.Samples.PivotControl?
And why are you using this rather than the standard one?

Resources