I want the text in a TextBox to get selected when the TextBox gets focused.
Therefore I need to binding a Command to the "GotFocus" event. The special thing is, that the TextBox is created dynamically via an ItemsControl.
So there is a binding to the UserControl (View), the ItemsControl and the Item itself. When I tried to bind the UI element to the CommandParameter I just got the Model bindet to the current item in the ItemsControl.
All the bindings are working perfectly except the CommandParameter..
Somebody got an idea how to get this working?
Here is my code:
XAML
/////// <UserControl/> Information:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
x:Name="MainBindingControl"
///////
<ItemsControl ItemsSource="{Binding MySecondModelList }" Margin="10,10,10,0">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid helper:GridHelper.RowCount="{Binding MyFirstModel.Rows}" helper:GridHelper.ColumnCount="{Binding MyFirstModel.Columns}">
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Row" Value="{Binding Row}" />
<Setter Property="Grid.Column" Value="{Binding Column}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Margin="25,25,25,25" Height="30" Width="30" Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" TextAlignment="Center" VerticalContentAlignment="Center" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<i:InvokeCommandAction Command="{Binding ElementName=MainBindingControl, Path=DataContext.TextBoxFocusCommand}" CommandParameter="{Binding RelativeSource={ RelativeSource Self }}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<TextBox.Style>
<Style TargetType="TextBox">
<Setter Property="Background" Value="OrangeRed" />
<Style.Triggers>
<Trigger Property="Text" Value="0">
<Setter Property="Background" Value="Orange" />
</Trigger>
<Trigger Property="Text" Value="1">
<Setter Property="Background" Value="White" />
</Trigger>
<Trigger Property="Text" Value="2">
<Setter Property="Background" Value="White" />
</Trigger>
<Trigger Property="Text" Value="3">
<Setter Property="Background" Value="White" />
</Trigger>
<Trigger Property="Text" Value="4">
<Setter Property="Background" Value="White" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
CS
#region TextBoxFocus
private ICommand _textBoxFocusCommand;
public ICommand TextBoxFocusCommand
{
get { return _textBoxFocusCommand; }
set { _textBoxFocusCommand = value; }
}
public void TextBoxFocus(object parameter)
{
var _tmp = parameter as TextBox;
if (_tmp != null )
{
_tmp.SelectAll();
}
}
#endregion
Models
public class FirstModel
{
public int Rows { get; set; }
public int Columns { get; set; }
}
public class SecondModel
{
public int Row { get; set; }
public int Column { get; set; }
public string Text { get; set; }
}
public class ViewModel
{
public FirstModel MyFirstModel { get; set; }
public ObservableCollection<SecondModel> MySecondModelList { get; set; }
}
Since what you want to do is only related to the view, I'd just add the code in the code-behind, instead of trying to use commands and get the TextBox inside the ViewModel. In MVVM you should NEVER reference UI assemblies from the ViewModel. But it is ok for you to use code-behind if what you are trying to do is only related to the View.
So, inside the style of the TextBox, you would have:
<EventSetter Event="GotFocus" Handler="TextBox_GotFocus"/>
And then in the code-behind of the UserControl:
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox textBox = sender as TextBox;
textBox.SelectAll();
}
The complete code of your DataTemplate would then be:
<DataTemplate>
<TextBox Margin="25,25,25,25" Height="30" Width="30" Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" TextAlignment="Center" VerticalContentAlignment="Center" >
<!-- Just erase this block of code
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<i:InvokeCommandAction Command="{Binding ElementName=MainBindingControl, Path=DataContext.TextBoxFocusCommand}" CommandParameter="{Binding RelativeSource={ RelativeSource Self }}"/>
</i:EventTrigger>
</i:Interaction.Triggers>-->
<TextBox.Style>
<Style TargetType="TextBox">
<EventSetter Event="GotFocus" Handler="TextBox_GotFocus"/>
<Setter Property="Background" Value="OrangeRed" />
<Style.Triggers>
<Trigger Property="Text" Value="0">
<Setter Property="Background" Value="Orange" />
</Trigger>
<Trigger Property="Text" Value="1">
<Setter Property="Background" Value="White" />
</Trigger>
<Trigger Property="Text" Value="2">
<Setter Property="Background" Value="White" />
</Trigger>
<Trigger Property="Text" Value="3">
<Setter Property="Background" Value="White" />
</Trigger>
<Trigger Property="Text" Value="4">
<Setter Property="Background" Value="White" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</DataTemplate>
Notice that the method SelectAll() of the TextBox called on GotFocus event has a little trick to work as intended. Check this SO question: How to automatically select all text on focus in WPF TextBox?
Related
I have a ComboBox with an ItemTemplateSelector, using 2 different DataTemplates, one for when its drop down is visible and another when it is not. For the drop down template, each ComboBox item is represented by a TextBlock and a Button that should only be visible whenever that item is focused/highlighted/mouse over. This is what I've tried:
<ComboBox x:Name="Windows" ItemsSource="{Binding Windows}" SelectedItem="{Binding Window}" Focusable="False" MaxDropDownHeight="238">
<ComboBox.ItemTemplateSelector>
<s:ComboBoxItemTemplateSelector>
<s:ComboBoxItemTemplateSelector.SelectedTemplate>
<DataTemplate>
<TextBlock Text="{Binding TitleShort}" ToolTip="{Binding Title}" />
</DataTemplate>
</s:ComboBoxItemTemplateSelector.SelectedTemplate>
<s:ComboBoxItemTemplateSelector.DropDownTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="{Binding TitleShort}" />
<Button Content="X">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsFocused, ElementName=Windows}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</StackPanel>
</DataTemplate>
</s:ComboBoxItemTemplateSelector.DropDownTemplate>
</s:ComboBoxItemTemplateSelector>
</ComboBox.ItemTemplateSelector>
<ComboBox.ItemContainerStyle>
<Style BasedOn="{StaticResource MaterialDesignComboBoxItemStyle}" TargetType="ComboBoxItem">
<Setter Property="ToolTip">
<Setter.Value>
<TextBlock Text="{Binding Title}" />
</Setter.Value>
</Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
public class ComboBoxItemTemplateSelector : DataTemplateSelector
{
public DataTemplate SelectedTemplate { get; set; }
public DataTemplate DropDownTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
ComboBoxItem comboBoxItem = GetVisualParent<ComboBoxItem>(container);
if (comboBoxItem == null)
{
return SelectedTemplate;
}
return DropDownTemplate;
}
private static T GetVisualParent<T>(object childObject) where T : Visual
{
DependencyObject child = childObject as DependencyObject;
while ((child != null) && !(child is T))
{
child = VisualTreeHelper.GetParent(child);
}
return child as T;
}
}
ComboBox generates ComboBoxItem as a container for every item in its itemssource. You can bind to its properties with RelativeSource binding.
This should get you the expected behavior:
<Button Content="X">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=ComboBoxItem}}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
I have two buttons. I want change second Button BackgroundColor using Triggers When I click first button but I am unable to do it. The code I am trying
<Button Text="button 1" x:Name="btn1" HorizontalOptions="Fill">
<Button.Triggers>
<Trigger TargetType="Button" Binding="{Binding Source={x:Reference btn2} Property="IsEnabled">
<Setter Property="BackgroundColor" Value="Red"></Setter>
</Trigger>
</Button.Triggers>
</Button>
<Button Text="button 2" x:Name="btn2" HorizontalOptions="Fill" />
I even have no idea where to write click event for this.
The best way to do that is to use ViewModel rather than the Code base.
Approach 1 : using the ViewModel
public class YourViewModel : BaseViewModel
{
public ICommand Button1Command { get; set; }
private bool _enableButton2;
public bool EnableButton2
{
get
{
return _enableButton2;
}
set
{
_enableButton2= value;
RaisePropertyChanged();
}
}
public YourViewModel()
{
Button1Command =new Command(Button1Clicked);
}
private void Button1Clicked()
{
EnableButton2=true; //Whenever you need to enable or disable set it true/false
}
}
Now you have your ViewModel, You need to implement your UI like this :
<Button x:Name="button1" Text="Button 1" Command="{Binding Button1Command }" />
<Button x:Name="button2" Text="Button 2">
<Button.Triggers>
<DataTrigger TargetType="Button" Binding="{Binding EnableButton2}" Value="false">
<Setter Property="BackgroundColor" Value="#dbe1e5" />
<Setter Property="TextColor" Value="#bfcfd5" />
</DataTrigger>
<DataTrigger TargetType="Button" Binding="{Binding EnableButton2" Value="true">
<Setter Property="BackgroundColor" Value="Red" />
<Setter Property="TextColor" Value="#FFFFFF" />
</DataTrigger>
</Button.Triggers>
</Button>
This is the MVVM way to do this; let me know if you want Code Base style.
I have an image that need to be showed based on condition, is that attachment file or not. The problem is, I've set trigger that set the value of the condition, but seems like the condition isn't work and the value always set to true.
<Image
Width="30"
Height="30"
Source="Resources/Images/chat_file_attach.png">
<Image.Style>
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<DataTrigger Binding="{Binding AttachStat}" Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
<DataTrigger Binding="{Binding AttachStat}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
The question is. Is there any way to make the default value to false? I've set it to true on the C# looping data, whenever the condition is attachment included.
Take a look in your output window and search for:
System.Windows.Data Warning: 40 : BindingExpression path error
I think the AttachStat property is not available in the image's DataContext.
Use a single DataTrigger and make sure that the DataContext of the Image has a public AttachStat property:
<Image x:Name="img" Width="30" Height="30" Source="Resources/Images/chat_file_attach.png">
<Image.Style>
<Style TargetType="{x:Type Image}">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding AttachStat}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
img.DataContext = new YourClass();
...
public class YourClass : INotifyPropertyChanged
{
private bool _attachStat;
public bool AttachStat
{
get
{
return _attachStat;
}
set
{
_attachStat = value;
NotifyPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
You can use a BoolToVisibilityConverter to convert a Boolean to and from a Visibility value.
In the resource section:
<BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter" />
And the image:
<Image Width="30"
Height="30"
Source="Resources/Images/chat_file_attach.png"
Visibility="{Binding AttachStat,
Converter={StaticResource BoolToVisibilityConverter}}" />
I'm trying to create a re-usable textblock user control in WPF. The basic idea is as follows:
User does not directly specify the content of the textblock
There are three dependancy properties in my user control called IsToggled, ToggleTrueText, and ToggleFalseText.
The control will display ToggleTrueText if IsToggled is true; or display ToggleFalseText if IsToggled is false.
When IsToggled changes during runtime, the text automatically changes to either ToggleTrueText or ToggleFalseText
I started by adding a PropertyChangedCallback to the IsToggled DP:
Code-behind of the UserControl:
public static readonly DependencyProperty IsToggledProperty =
DependencyProperty.Register("IsToggled", typeof(bool),
typeof(TagToggle), new PropertyMetadata(new
PropertyChangedCallback(OnToggleStateChanged)));
public bool IsToggled
{
get { return (bool)GetValue(IsToggledProperty); }
set { SetValue(IsToggledProperty, value); }
}
//ToggleTrueText and ToggleFalseText are declared similarly to IsToggled
...
private static void OnToggleStateChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
...
}
Xaml of the user control:
<Grid x:Name="LayoutRoot">
<TextBlock x:Name="TheTextBlock" Text="{Binding WhatDoIBindTo}"/>
</Grid>
However, I'm not sure what would be the best way to ensure that TheTextBlock updates its text whenever IsToggled changes during runtime.
Try this:
private static void OnToggleStateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TagToggle ctrl = d as TagToggle;
if (ctrl != null)
{
TheTextBlock.Text = ctrl.IsToggled ? ToggleTrueText. : ToggleFalseText;
}
}
If you want to bind the Text property of the TextBlock you need to make sure that you are binding to properties of the UserControl. You could do this by setting the DataContext property of the TextBlock:
<TextBlock x:Name="TheTextBlock" DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Text" Value="{Binding ToggleTrueText}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsToggled}" Value="False">
<Setter Property="Text" Value="{Binding ToggleFalseText}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
You can used trigger for this
Please check below code
<TextBlock x:Name="TheTextBlock">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsToggled}" Value="True">
<Setter Property="Text" Value="{Binding ToggleTrueText}"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsToggled}" Value="False">
<Setter Property="Text" Value="{Binding ToggleFalseText}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
I have different ControlTemplates for one Canvas:
<Application.Resources>
<ControlTemplate x:Key="Control1" />
<ControlTemplate x:Key="Control2" />
</Application.Resources>
I want to change one of them by my viewmodel property like this:
private string _template = "Control1";
public string Template
{
get
{
return _template;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_template = value;
OnPropertyChanged("Template");
}
}
}
And finally use it in my view:
<UserControl Template="{StaticResource {Binding Template}}" />
But it doesn't work, how i can fix it?
Thanks
You can try using DataTriggers
<UserControl>
<UserControl.Style>
<Style TargetType="{x:Type UserControl}">
<Setter Property="ControlTemplate" value="{StaticResource Control1}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Template}" Value ="Control1">
<Setter Property="ControlTemplate" value="{StaticResource Control1}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Template}" Value ="Control2">
<Setter Property="ControlTemplate" value="{StaticResource Control2}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Style>
</UserControl>