How can I detect my keyboard without press enter C# WPF - c#

How can i change this code to active detecion of my keyboard. Now it is showing what i write after press enter. How can i show what i can write without enter key.
XAML:
<StackPanel>
<TextBlock Width="300" Height="20">
Type some text into the TextBox and press the Enter key.
</TextBlock>
<TextBox Width="300" Height="30" Name="textBox1"
KeyDown="OnKeyDownHandler"/>
<TextBlock Width="300" Height="100" Name="textBlock1"/>
</StackPanel>
C#:
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
textBlock1.Text = "You Entered: " + textBox1.Text;
}
}
Or maybe is some diffrent way to create it?

You could simply bind the text directly:
<StackPanel>
<TextBlock Width="300" Height="20">
Type some text into the TextBox and it will appear in the field automatically.
</TextBlock>
<TextBox Width="300" Height="30" Name="textBox1" />
<TextBlock Width="300" Height="100" Name="textBlock1" Text="{Binding Text, ElementName=textbox1}"/>
</StackPanel>
This way you don't need any code-behind.
EDIT
If you want more sophisticated stuff, try this. Implement a new class in your project like this:
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return $"You entered: {value ?? "nothing"}";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
and then change your binding to
<Window.Resources>
<local:MyConverter x:Key="MyConverter"/>
</Window.Resources>
<StackPanel>
<TextBox Name="txtEdit" />
<TextBlock Text="{Binding Text, Converter={StaticResource MyConverter}, ElementName=txtEdit}" />
</StackPanel>
Don't forget the resources for the window.
Here is a screen video showing it in action:

textBlock1.Text = "You Entered: " + **textBox1.Text**;
Don't use direct control property, in contrast use MVVM and binding.
"The UpdateSourceTrigger property of a binding controls how and when a changed value is sent back to the source."
http://www.wpf-tutorial.com/data-binding/the-update-source-trigger-property/

If I correctly understood the question, you need tunneling PreviewKeyDown event:
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.G)
{
e.Handled = true;
}
}
Alternatively, you can you use Keyboard class. In fact, Keyboard class can be used anywhere in your code:
private void SomeMethod()
{
if (Keyboard.IsKeyDown(Key.LeftCtrl))
{
MessageBox.Show("Release left Ctrl button");
return;
}
//Do other work
}

Related

How to focus into AutoCompleteBox

How to focus into AutoCompleteBox? I've tried many of code by searching on stackover but not getting focus. here is some code which i wrote.
<controls:AutoCompleteBox Name="SearchTextBox" IsTextCompletionEnabled="True" SelectedItem="{Binding Code, Mode=TwoWay}" Grid.Column="1" PreviewKeyDown="SearchTextBox_PreviewKeyDown" >
<controls:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Code}"/>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</controls:AutoCompleteBox.ItemTemplate>
</controls:AutoCompleteBox>
and for focus i've creating a class named FocusableAutoCompleteBox
public class FocusableAutoCompleteBox : AutoCompleteBox
{
public new void Focus()
{
var textbox = Template.FindName("SearchTextBox", this) as AutoCompleteBox;
if (textbox != null) textbox.Focus();
}
}
and focus by
new FocusableAutoCompleteBox().Focus();
but errors appears
Object Reference not set to an instance of object
I also tried SearchTextBox.Focus(); but not getting result.
this works for me.
Keyboard.Focus(SearchTextBox);
SearchTextBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

Getting Control of RadioButton WPF

Here what i have in xaml:
<DataGrid Name="dataGrid">
<DataGridTemplateColumn Header = "Base" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<RadioButton Grid.Column="0" GroupName="{Binding Index}" Name="ABCD" Content="ABCD" IsChecked="True" Checked="radioButton_Checked"/>
<RadioButton Grid.Column="1" GroupName="{Binding Index}" Name="XYZ" Content="XYZ" Checked="radioButton_Checked" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid>
Here are some codes in some function (any) xaml.cs:
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
FrameworkElement radioButton = dataGrid.Columns[0].GetCellContent(row) as FrameworkElement;
radioButton.Visibility = Visibility.Hidden;
I can hide the visibility as I am hiding whole cell. but i want to change a radio button content in runtime from "XYZ" to "HAHAHA". How can i achieve this?
You might be able to use a value converter to achieve this. This can be used to change the name based on the index value;
public class IndexToXYZOrHaHaHaConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var index = (int) value;
if (index > 10)
{
return "XYZ";
}
return "HaHaHa";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
You'll need to create an instance of the class by adding a static resource to your resource dictionary.
<local:IndexToXYZOrHaHaHaConverter x:Key="IndexToXYZOrHaHaHaConverter"/>
You'll then need to change the content of the radio button from "xyz" to this;
Content="{Binding Index, Converter={StaticResource IndexToXYZOrHaHaHaConverter}}"
This should dynamically switch the value between xyz and HaHaHa depending on the index. In the example I gave this depends on whether the value is greater or less than 10, which is probably not what you want so you'll have to fix the logic. I've also assumed that index is an integer, you may need to change that too if index is something else.
Converters are great for setting properties based on bound values that don't directly correspond to the value they are bound to e.g. converting a string to a color.
Hope this is of some help.

Unable to update binded control in Silverlight view

XAML code:
<TextBlock Text="Country" Foreground="white" TextAlignment="Right" Grid.Row="2" Grid.Column="0" />
<TextBox
x:Name="txtCountries"
Grid.Row="2"
Grid.Column="1"
Grid.ColumnSpan="2"
HorizontalAlignment="Stretch"
Margin="2, 2, 2, 2"
Text="{Binding PhysicalDeliveryParameters.Countries, Converter={StaticResource EnumerableToTextConverter}, ConverterParameter='...'}"
IsReadOnly="True">
</TextBox>
<Button
Grid.Row="2"
Grid.Column="3"
Content="..."
HorizontalAlignment="Left"
Tag="Countries"
Click="ButtonBase_OnClick" />
C# code :
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
PhysicalDeliveryParametersViewModel pvm = GetViewModel();
GenericObservableCollection<SelectableItem> items = pvm.Countries;
PhysicalDeliveryParametersDlg dlg = new PhysicalDeliveryParametersDlg(items);
dlg.Closed += (o, args) =>
{
BindingExpression binding = txtCountries.GetBindingExpression(TextBox.TextProperty);
if(null != binding)
binding.UpdateSource();
};
dlg.ShowDialog();
}
When I click on the button, the ButtonBase_OnClick() method executes : a dialog appears (PhysicalDeliveryParametersDlg class) and I choose some values. The binded data (PhysicalDeliveryParameters.Countries, which is an ObservableCollection) is updated, but not the Text property of my TextBox... Did I do something wrong ?
PS : I'm not sure I use the best method to create a modal window in Silverlight, could you give me some advice ?
It looks like the problem is that PropertyChanged never gets raised on the "Countries" property, so the view doesn't know it needs to update. (Actually, it probably wouldn't help to raise "PropertyChanged" in this case -- since the object reference has not changed, I believe the runtime would ignore it.)
I would just add another property "CountriesString" or similar:
Text="{Binding PhysicalDeliveryParameters.CountriesString}"
Update the property whenever is appropriate:
dlg.Closed += (o, args) =>
{
pvm.CountriesString = string.Join(", ", pvm.Countries);
};

Windows Phone update/refresh binding

I have a textblock in my listbox called "feedTitle" which I want to change the forground color of. I use Foreground="{Binding Converter={StaticResource NewsTextColorConverter}}" for the binding of the forground color. Now the strange problem is that, if I choose a color in the listpicker("Lys" or "Dark" value) it runs the IValueConverter Convert method, but it dont show the color in the GUI, only if I restart my whole app it shows the color I chosen. It's like it only set the color of the forground of the textblock once.
MainPage.xaml
<ListBox Grid.Row="1" Name="feedListBox" ScrollViewer.VerticalScrollBarVisibility="Auto" SelectionChanged="feedListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Top">
<TextBlock TextDecorations="Underline" FontSize="24" Name="feedTitle" TextWrapping="Wrap" Margin="12,0,0,0" Foreground="{Binding Converter={StaticResource NewsTextColorConverter}}" Text="{Binding Title.Text, Converter={StaticResource RssTextTrimmer}}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And in my app file:
App.xaml
<Application.Resources>
<converter:NewsTextColorConverter xmlns:converter="clr-namespace:NordjyskeRss" x:Key="NewsTextColorConverter" />
</Application.Resources>
I use a listpicker where a user select the value "Mørk" or "Lys" and then I want the textblock forground color to update its forground color. I call the Convert method and pass null as arguments, it seems to run the method fine:
MainPage.cs
private void lpkThemes_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Make sure we don't handle the event during initiation.
if (e.RemovedItems != null && e.RemovedItems.Count > 0)
{
if (this.lpkThemes.SelectedItem != null)
{
settings[THEMES_SETTING_KEY] = lpkThemes.SelectedItem.ToString();
if (lpkThemes.SelectedItem.ToString() == "Mørk")
{
n.Convert(null, null, null, null);
}
else
{
n.Convert(null, null, null, null);
}
}
}
}
This is where I use a IValueConverter to check for what color to use on the textblock and then add it:
MainPage.cs
public class NewsTextColorConverter : IValueConverter
{
protected IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
protected const string THEMES_SETTING_KEY = "Themes";
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (settings.Contains(THEMES_SETTING_KEY))
{
string themesValue = (string)settings[THEMES_SETTING_KEY];
if (themesValue == "Mørk")
{
return new SolidColorBrush(Colors.Green);
}
else
{
return new SolidColorBrush(Colors.Blue);
}
}
return new SolidColorBrush(Colors.Green);
//throw new NotSupportedException("ColorToBurshConverter only supports converting from Color and String");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
I think you need to redesign your app in the following way:
Add the following line into your app.xaml or page resources: <SolidColorBrush x:Key="brushListItemsForeground" Color="#FFFFFFFF" />
Replace Foreground="{Binding Converter={StaticResource NewsTextColorConverter}}" with Foreground="{StaticResource brushListItemsForeground}"
In your SelectionChanged:
var brush = (SolidColorBrush)Application.Current.Resources["brushListItemsForeground"]; if you’ve added the brush to app.xaml, or = (SolidColorBrush)this.Resources["brushListItemsForeground"]; if you’ve added the brush to page resources. Then change the Color property of the brush based on your settings.
P.S. There’re also other correct ways: e.g. create a SettingsContainer class that implements INotifyPropertyChanged, add it into some resource dictionary <local:SettingsContainer x:Key="mySettings" />, then bind to its properties e.g. Foreground="{Binding listItemsForeground, Source={StaticResource mySettings}}", when you need to change the value, change the listItemsForeground property of your class and raise PropertyChanged.
Currently, you’re abusing value converter using then as value providers, they were not designed for that, and that is why you have issues updating those values.

How add and show tooltip textbox WPF if textbox not empty

Need to show a hint, which contains data from a text field. Prompt to appear if the textbox has data.
Just use binding to ToolTipService attached properties. XAML:
<UserControl.Resources>
<converters:IsStringNonemptyConverter x:Key="ToolTipVisibilityConveter" />
</UserControl.Resources>
<TextBox Name="textBox" VerticalAlignment="Center" HorizontalAlignment="Center" Width="150"
ToolTipService.ToolTip="{Binding Text, RelativeSource={RelativeSource Self}}"
ToolTipService.IsEnabled="{Binding Text, RelativeSource={RelativeSource Self}, Converter={StaticResource ToolTipVisibilityConveter}}"/>
Converter:
internal sealed class IsStringNonemptyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return !String.IsNullOrEmpty(value as string);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
You can disable the tooltip using triggers. Place this style in your window or App resources so that it can be shared across all the textboxes in your window or application depending on your choice -
<Style x:Key="{x:Type TextBox}" TargetType="TextBox">
<Style.Triggers>
<Trigger Property="ToolTip" Value="{x:Static sys:String.Empty}">
<Setter Property="ToolTipService.IsEnabled" Value="False" />
</Trigger>
</Style.Triggers>
Make sure you add the system namespace to your xaml -
xmlns:sys="clr-namespace:System;assembly=mscorlib"
I had this problem myself and figured out a different solution. I know this question has been answered but just like me there will still be people coming across this question, and I would like to share my solution:
XAML
<TextBox Name="textBox1" ToolTip="{Binding Text, RelativeSource={RelativeSource Self}}" ToolTipService.IsEnabled="False"/>
Code behind
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (textBox1.Text.Length > 0)
{
ToolTipService.SetIsEnabled(textBox1, true);
}
}
I hope this helps someone.
I tried with Visibility Mode & TextChange event. ToolTip invisible when no text. May be useful for someother.
Xaml:
<TextBox Height="23" Width="100" Name="myTextBox" TextChanged="myTextBox_TextChanged" >
<TextBox.ToolTip>
<ToolTip Visibility="Hidden">
<TextBlock Name="toolTipTextBlock"></TextBlock>
</ToolTip>
</TextBox.ToolTip>
</TextBox>
TextChange event handler:
private void myTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb.Text.Trim() == "")
{
((ToolTip)tb.ToolTip).Visibility = Visibility.Hidden;
}
else
{
toolTipTextBlock.Text = tb.Text;
((ToolTip)tb.ToolTip).Visibility = Visibility.Visible;
}
}

Categories

Resources