I'm working on a Windows Phone app using Silverlight C# and XAML. My page contains a ListBox which renders a list of databound objects that the user can manipulate, i.e. add/rename/delete.
I've got it working that the add/rename of items is done in-place, i.e. by swapping a TextBlock for a TextBox depending on the state of the object (bool IsEditable property) and making use of a parameterized VisibilityConverter to manage the opposite Visibility states.
<UserControl.Resources>
<local:VisibilityConverter x:Key="VisibilityConverter" True="Visible" False="Collapsed"/>
<local:VisibilityConverter x:Key="InvertedVisibility" True="Collapsed" False="Visible"/>
</UserControl.Resources>
...
<TextBlock Text="{Binding Name}" Visibility="{Binding IsEditable, Converter={StaticResource InvertedVisibility}}" />
<TextBox Text="{Binding Name}" Visibility="{Binding IsEditable, Converter={StaticResource VisibilityConverter}}"/>
The thing is that I also want the TextBox to automatically grab focus when it becomes visible, so that the on-screen keyboard pops up without the user having to tap the TextBox.
Since there's no VisibilityChanged event on a regular TextBox, I subclassed TextBox to TextBox2 and added my own:
public class TextBox2 : TextBox
{
public TextBox2()
{
DefaultStyleKey = typeof(TextBox);
}
public static readonly DependencyProperty VisibilityChangedProperty = DependencyProperty.Register(
"VisibilityChanged",
typeof(string),
typeof(TextBox2),
new PropertyMetadata("Set the VisibilityChanged event handler"));
public event VisibilityChangedEventHandler VisibilityChanged;
public delegate void VisibilityChangedEventHandler(object sender, EventArgs e);
public new Visibility Visibility
{
get
{
return base.Visibility;
}
set
{
if (base.Visibility != value)
{
base.Visibility = value;
VisibilityChanged(this, new EventArgs());
}
}
}
}
Now my XAML looks like this:
<TextBlock Text="{Binding Name}" Visibility="{Binding IsEditable, Converter={StaticResource InvertedVisibility}}"/>
<local:TextBox2 Text="{Binding Name}" Visibility="{Binding IsEditable, Converter={StaticResource VisibilityConverter}}" VisibilityChanged="ListEdit_VisibilityChanged"/>
And the event handler like this:
void ListEdit_VisibilityChanged(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Visibility == System.Windows.Visibility.Collapsed)
return;
textBox.Focus();
}
The TextBox2 renders properly and behaves just like a TextBox at runtime, but my VisibilityChanged event handler is not firing when the databinding flips the value of IsEditable.
IsEditable defines the Visibility and the TextBox2 does become visible correctly, so the databinding is working.
I can cause the event to fire programmatically by getting hold of the TextBox2 instance and setting the Visibility of that in code. That also works.
But this databinding scenario being responsible for setting the Visibility seems not to work.
Any ideas why not?
Here are 2 solutions that I use.
Solution 1 needs no sub class, but solution 2 is more reusable.
1. You can subscribe to the Loaded event of the TextBox, and force a focus, like so:
void TextBox_Loaded_Focus(object sender, System.Windows.RoutedEventArgs e) {
ForceFocusControl((Control)sender);
}
void ForceFocusControl(Control control) {
control.Focus();
if (FocusManager.GetFocusedElement() != control) {
Dispatcher.BeginInvoke(() => ForceFocusControl(control));
}
}
This solution goes into a recursive loop though, you might want to add some checks to make it safer.
2. Keep your subclass TextBox2, and rather create a private MyVisibility dependency property that you bind to the Visibility property of the base class, but also specify a DependencyProperty_Changed handler, like so:
/// <summary>
/// <see cref="TextBox2"/> will focus itself when it becomes visible.
/// </summary>
public sealed class TextBox2 : TextBox {
public TextBox2() {
SetBinding(TextBox2.MyVisibilityProperty, new Binding("Visibility") { Source = this });
}
static readonly DependencyProperty MyVisibilityProperty = DependencyProperty.Register(
/* name = */ "MyVisibilityProperty",
/* property type = */ typeof(Visibility),
/* owner type = */ typeof(TextBox2),
/* meta = */ new PropertyMetadata(MyVisibilityProperty_Changed));
static void MyVisibilityProperty_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) {
TextBox2 TextBox2 = (TextBox2)d;
if (TextBox2.Visibility == Visibility.Visible) {
TextBox2.Focus();
}
}
}
This is how my TextBox2 class looks now:
public class TextBox2 : TextBox
{
public event VisibilityChangedEventHandler VisibilityChanged;
public delegate void VisibilityChangedEventHandler(object sender, EventArgs e);
public static readonly DependencyProperty VisibilityChangedProperty = DependencyProperty.Register(
"VisibilityChanged", typeof(VisibilityChangedEventHandler), typeof(TextBox2), null);
static readonly DependencyProperty MirrorVisibilityProperty = DependencyProperty.Register(
"MirrorVisibility", typeof(Visibility), typeof(TextBox2), new PropertyMetadata(MirrorVisibilityChanged));
public TextBox2()
{
SetBinding(TextBox2.MirrorVisibilityProperty, new Binding("Visibility") { Source = this });
}
static void MirrorVisibilityChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
((TextBox2)obj).VisibilityChanged(obj, null); // raise event
}
}
Related
I have very basic question regarding dependency property and data-binding. I have created a simple class name TDTVm its my ViewModel class. It has one bool dependency property named IsShaftMovingUp and its initial value is 'False' I have bound this value to one text box on UI. Now I want to show real-time value of 'IsShaftMovingUp' on the screen.
Below is my VM.
public class TDTVm : DependencyObject
{
public static DependencyProperty ShaftMovingUpProperty =
DependencyProperty.Register(
"ShaftMovingUp",
typeof(bool),
typeof(TDTVm),
new PropertyMetadata(false, ShaftMovingUpChanged));
private static void ShaftMovingUpChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine("ok");
}
public bool IsShaftMovingUp
{
get => (bool)GetValue(TDTVm.ShaftMovingUpProperty);
set => SetValue(TDTVm.ShaftMovingUpProperty, value);
}
}
Below is my xamal code.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Button Content="Button" Click="Button_Click"/>
<TextBox Text="{Binding IsShaftMovingUp,
UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>
and below is my code behind:
public partial class MainWindow : Window
{
TDTVm datacontext = new TDTVm();
public MainWindow()
{
InitializeComponent();
this.DataContext = datacontext;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
///Even after this line 'true' value is not getting updated on UI.
datacontext.IsShaftMovingUp = true;
}
}
When I click on button I am setting value of 'IsShaftMovingUp' to true. But still on UI its not getting updated. ( I have achieved this using INotifyPropertyChanged but want to try same with dependency property to understand exact difference between the two )
Thanks
To fix your problem, you need to change this code
DependencyProperty.Register("ShaftMovingUp",
into
DependencyProperty.Register("IsShaftMovingUp",
Check this post, if you want to know the difference between INotifyPropertyChanged and Dependency Property.
I am having a master window in which there are plenty of user control. and using navigation i am able to access the user controls. But by question is how to set focus on the first text box when ever the user control is opened.
I tried with dependency property and boolean flags, i was able to succeeded a bit. When i first render the UserControl i was able to focus but when i open for the second time i was not able to set focus on the TextBox.
And one more thing, i have validation for TextBoxes, if the validation fails then the textbox should be emptied and the focus should be on the respective text box.
How can i achieve this using MVVM in WPF (CLR 3.5, VS2008)
thanks in advance.
If you have a UserControl then you also have CodeBehind.
Place this inside your codebehind and you will do fine.
this.Loaded += (o, e) => { Keyboard.Focus(textBox1) }
Place this inside your UserControl XAML if you wish to listen to validation errors.
<UserControl>
<Grid Validation.Error="OnValidationError">
<TextBox Text{Binding ..., NotifyOnValidationError=true } />
</Grid>
<UserControl>
Inside the CodeBehind of your UserControl you will have something like this:
public void OnValidationError(o , args)
{
if(o is TextBox)
{
(TextBox)o).Text = string.Empty;
}
}
You should use AttachedProperty to stick to MVVM pattern it'll keep your view model independent of UI code and fully unit testable. Following attached property binds a boolean property to focus and highlight the TextBox, if you do not want the highlighting then you can remove the highlighting code and just work with focus code.
public class TextBoxBehaviors
{
#region HighlightTextOnFocus Property
public static readonly DependencyProperty HighlightTextOnFocusProperty =
DependencyProperty.RegisterAttached("HighlightTextOnFocus", typeof (bool), typeof (TextBoxBehaviors),
new PropertyMetadata(false, HighlightTextOnFocusPropertyChanged));
public static bool GetHighlightTextOnFocus(DependencyObject obj)
{
return (bool) obj.GetValue(HighlightTextOnFocusProperty);
}
public static void SetHighlightTextOnFocus(DependencyObject obj, bool value)
{
obj.SetValue(HighlightTextOnFocusProperty, value);
}
private static void HighlightTextOnFocusPropertyChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
var uie = sender as UIElement;
if (uie == null) return;
if ((bool) e.NewValue)
{
uie.GotKeyboardFocus += OnKeyboardFocusSelectText;
uie.PreviewMouseLeftButtonDown += OnMouseLeftButtonDownSetFocus;
}
else
{
uie.GotKeyboardFocus -= OnKeyboardFocusSelectText;
uie.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDownSetFocus;
}
}
private static void OnKeyboardFocusSelectText(object sender, KeyboardFocusChangedEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) return;
textBox.SelectAll();
}
private static void OnMouseLeftButtonDownSetFocus(object sender, MouseButtonEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) return;
if (!textBox.IsKeyboardFocusWithin)
{
textBox.Focus();
e.Handled = true;
}
}
#endregion
}
You can use this attached property in on your TextBox which you want to focus/highlight...
<TextBox ... local:TextBoxBehaviors.HighlightTextOnFocus="{Binding IsScrolledToEnd}" ... />
You can also try using FocusManager
<UserControl>
<Grid FocusManager.FocusedElement="{Binding Path=FocusedTextBox, ElementName=UserControlName}">
<TextBox x:Name="FocusedTextBox" />
</Grid>
<UserControl>
I have a WPF user control that has a DependencyProperty called IsMultiSelect. I want to show hide a Button in the UserControl xaml.
<Button Visibility="{Binding IsMultiSelect, Converter=....}" />
This user control has a ViewModel assigned to the DataContext.
The above syntax gives me a binding error due to the property not existing in the view model.
How can I fix this error?
You can target the UserControl in different ways in the binding.
One solution would be to find it by setting a RelativeSource like this:
<Button Visibility="{Binding IsMultiSelect,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}},
Converter=....}" />
Instead of binding to the property from xaml, the property changed handler for the dependency property should change the button's visibility.
public static readonly DependencyProperty IsMultiSelectProperty = DependencyProperty.Register("IsMultiSelect", typeof(bool), typeof(MyUserControl), new PropertyMetadata(false, OnIsMultiSelectPropertyChanged));
private static void OnIsMultiSelectPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
(sender as MyUserControl).OnIsMultiSelectPropertyChanged(e);
}
private void OnIsMultiSelectPropertyChanged(DependencyPropertyChangedEventArgs e)
{
MyButton.Visibility = (bool)e.NewValue ? Visibility.Visible : Visibility.Collapsed;
}
public bool IsMultiSelect
{
get { return (bool)GetValue(IsMultiSelectProperty); }
set { SetValue(IsMultiSelectProperty, value); }
}
And you can put the converter logic inside OnIsMultiSelectPropertyChanged as well.
I have a TabControl with many TabItems binding to a ViewModel that has properties for each TabItem's Visibility.
<sdk:TabControl>
<sdk:TabItem Name="Inventory" Header="Inventory"
Style="{StaticResource TabItemStyle}"
Visibility="{Binding Permissions.Inventory,
Converter={StaticResource PermissiveVisibilityConverter},
ConverterParameter='Viewer'}"
DataContext="{Binding VM}" />
</sdk:TabControl>
All TabItems are defaulted to a Visibility of collapsed. But when the VM changes a TabItem to Visible it does not work until you move your mouse over the control...
Even if I set the visibility programmatically with a button it behaves the same way!
I have checked to see if the VM's properties are Notifying the UI, and they are with NotifyOnPropertyChanged. And if I bind the data to a button's visibility it works just fine...It is just the TabItems that seem to have a bug.
Is there a way to get the TabItem UI to refresh? Or a work-around for this?
Thanks!
I've faced the same problem and I was able to overcome it using a attached "Visibility" property instead the original one. In this new property, I can pass the value to the original "Visibility" property and, in case the parent tab control's "SelectedItem" is being collapsed select the next visible tabItem.
However, as noted here, only that may not be enough if the first item is collapsed when the TabControl loads. This case had to be fixed in the TabControl itself, because tests showed when the fake "Visility" is set for the first time the TabItem does not have access to it's TabControl yet. Because of that I also used a attached property for the TabControl which corrects this issue.
The complete solution:
public static class TabControlExtensions
{
/// <summary>
/// Use this property on a TabControl to correct the behavior
/// of selecting Collapsed TabItems.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static bool GetSelectOnlyVisibleTabs(DependencyObject obj)
{
return (bool)obj.GetValue(SelectOnlyVisibleTabsProperty);
}
public static void SetSelectOnlyVisibleTabs(DependencyObject obj, bool value)
{
obj.SetValue(SelectOnlyVisibleTabsProperty, value);
}
public static readonly DependencyProperty SelectOnlyVisibleTabsProperty =
DependencyProperty.RegisterAttached("SelectOnlyVisibleTabs", typeof(bool), typeof(TabControlExtensions), new PropertyMetadata(false, SelectOnlyVisibleTabsChanged));
public static void SelectOnlyVisibleTabsChanged(object sender, DependencyPropertyChangedEventArgs args)
{
var tabControl = sender as TabControl;
if (tabControl == null) return;
if ((bool)args.NewValue)
{
tabControl.SelectionChanged += TabControl_SelectionChanged;
CorrectSelection(tabControl);
}
else
{
tabControl.SelectionChanged -= TabControl_SelectionChanged;
}
}
private static void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs args)
{
var tabControl = sender as TabControl;
if (tabControl == null) return;
CorrectSelection(tabControl);
}
public static void CorrectSelection(TabControl tabControl)
{
var selected = tabControl.SelectedItem as UIElement;
if (selected == null) return;
// If the selected element is not suposed to be visible,
// selects the next visible element
if (selected.Visibility == System.Windows.Visibility.Collapsed)
tabControl.SelectedItem = tabControl.Items.OfType<UIElement>()
.Where(e => e.Visibility == System.Windows.Visibility.Visible)
.FirstOrDefault();
}
}
public static class TabItemExtensions
{
/// <summary>
/// Use this property in a TabItem instead of the original "Visibility" to
/// correct the behavior of a TabControl when a TabItem's Visibility changes.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static Visibility GetVisibility(DependencyObject obj)
{
return (Visibility)obj.GetValue(VisibilityProperty);
}
public static void SetVisibility(DependencyObject obj, Visibility value)
{
obj.SetValue(VisibilityProperty, value);
}
public static readonly DependencyProperty VisibilityProperty =
DependencyProperty.RegisterAttached("Visibility", typeof(Visibility), typeof(TabItemExtensions), new PropertyMetadata(Visibility.Visible, VisibilityChanged));
public static void VisibilityChanged(object sender, DependencyPropertyChangedEventArgs args)
{
var tabItem = sender as TabItem;
if (tabItem == null) return;
var visibility = (Visibility)args.NewValue;
if (tabItem.Visibility == visibility) return;
tabItem.Visibility = visibility;
if (visibility == Visibility.Visible) return;
// Finds the tab's parent tabcontrol and corrects the selected item,
// if necessary.
var tabControl = tabItem.Ancestors().OfType<TabControl>().FirstOrDefault();
if (tabControl == null) return;
TabControlExtensions.CorrectSelection(tabControl);
}
}
The usage:
<sdk:TabControl local:TabControlExtensions.SelectOnlyVisibleTabs="True">
<sdk:TabItem Header="tabItem1" Visibility="Collapsed">
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="TabItem1 which should not be visible (1)" />
</sdk:TabItem>
<sdk:TabItem Header="tabItem2">
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="TabItem2 which should be visible (2)" />
</sdk:TabItem>
<sdk:TabItem DataContext="{Binding ViewModel}"
Header="tabItem3"
local:TabItemExtensions.Visibility="{Binding MyProperty,
Converter={StaticResource BoolToVisibilityConverter}}">
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="TabItem with binded Visibility (3)" />
</sdk:TabItem>
</sdk:TabControl>
What if you change the xaml so that you're setting the DataContext first:
<sdk:TabItem Name="Inventory" Header="Inventory"
Style="{StaticResource TabItemStyle}"
DataContext="{Binding VM}"
Visibility="{Binding Permissions.Inventory,
Converter={StaticResource PermissiveVisibilityConverter},
ConverterParameter='Viewer'}" />
I'm assuming that Permissions.Inventory is a property on your view model but since you haven't set the context at that point it seems like the binding shouldn't work.
Also, is your converter being hit if you set a breakpoint and if the getter on Permissions.Inventory being called?
I'm using Silverlight on Windows Phone 7.
I want to display the first part of some text in a TextBlock in bold, and the rest in normal font. The complete text must wrap. I want the bolded part to contain text from one property in my ViewModel, and the plain text to contain text from a different property.
The TextBlock is defined in a DataTemplate associated with a LongListSelector.
My initial attempt was:
<TextBlock TextWrapping="Wrap">
<TextBlock.Inlines>
<Run Text="{Binding Property1}" FontWeight="Bold"/>
<Run Text="{Binding Property2}"/>
</TextBlock.Inlines>
</TextBlock>
This fails at runtime with the spectacularly unhelpful "AG_E_RUNTIME_MANAGED_UNKNOWN_ERROR". This is a known issue because the Run element is not a FrameworkElement and cannot be bound.
My next attempt was to put placeholders in place, and then update them in code:
<TextBlock Loaded="TextBlockLoaded" TextWrapping="Wrap">
<TextBlock.Inlines>
<Run FontWeight="Bold">Placeholder1</Run>
<Run>Placeholder2</Run>
</TextBlock.Inlines>
</TextBlock>
In the code-behind (yes I am desparate!):
private void TextBlockLoaded(object sender, RoutedEventArgs e)
{
var textBlock = (TextBlock)sender;
var viewModel = (ViewModel)textBlock.DataContext;
var prop1Run = (Run)textBlock.Inlines[0];
var prop2Run = (Run)textBlock.Inlines[1];
prop1Run.Text = viewModel.Property1;
prop2Run.Text = viewModel.Property2;
}
This seemed to work, but because I am using the LongListSelector, although items get recycled, the Loaded codebehind event handler doesn't re-initialize the Runs, so very quickly the wrong text is displayed...
I've looked at using the LongListSelector's Linked event (which I already use to free up images that I display in the list), but I can't see how I can use that to re-initialize the Runs' text properties.
Any help appreciated!
I finally found a solution that works for me.
As I mention in the comment, Paul Stovell's approach would not work.
Instead I used a similar approach to add an attached property to the TextBlock, bound to the TextBlock's DataContext, and attached properties on the runs, indicating which ViewModel properties they should be bound to:
<TextBlock TextWrapping="Wrap"
Views:BindableRuns.Target="{Binding}">
<TextBlock.Inlines>
<Run FontWeight="Bold" Views:BindableRuns.Target="Property1"/>
<Run Views:BindableRuns.Target="Property2"/>
</TextBlock.Inlines>
</TextBlock>
Then in my attached TextBox Target (datacontext) property's changed event, I update the Runs, and subscribe to be notified of changes to the TextBox Target properties. When a TextBox Target property changes, I updated any associated Run's text accordingly.
public static class BindableRuns
{
private static readonly Dictionary<INotifyPropertyChanged, PropertyChangedHandler>
Handlers = new Dictionary<INotifyPropertyChanged, PropertyChangedHandler>();
private static void TargetPropertyPropertyChanged(
DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs e)
{
if(!(dependencyObject is TextBlock)) return;
var textBlock = (TextBlock)dependencyObject;
AddHandler(e.NewValue as INotifyPropertyChanged, textBlock);
RemoveHandler(e.OldValue as INotifyPropertyChanged);
InitializeRuns(textBlock, e.NewValue);
}
private static void AddHandler(INotifyPropertyChanged dataContext,
TextBlock textBlock)
{
if (dataContext == null) return;
var propertyChangedHandler = new PropertyChangedHandler(textBlock);
dataContext.PropertyChanged += propertyChangedHandler.PropertyChanged;
Handlers[dataContext] = propertyChangedHandler;
}
private static void RemoveHandler(INotifyPropertyChanged dataContext)
{
if (dataContext == null || !Handlers.ContainsKey(dataContext)) return;
dataContext.PropertyChanged -= Handlers[dataContext].PropertyChanged;
Handlers.Remove(dataContext);
}
private static void InitializeRuns(TextBlock textBlock, object dataContext)
{
if (dataContext == null) return;
var runs = from run in textBlock.Inlines.OfType<Run>()
let propertyName = (string)run.GetValue(TargetProperty)
where propertyName != null
select new { Run = run, PropertyName = propertyName };
foreach (var run in runs)
{
var property = dataContext.GetType().GetProperty(run.PropertyName);
run.Run.Text = (string)property.GetValue(dataContext, null);
}
}
private class PropertyChangedHandler
{
private readonly TextBlock _textBlock;
public PropertyChangedHandler(TextBlock textBlock)
{
_textBlock = textBlock;
}
public void PropertyChanged(object sender,
PropertyChangedEventArgs propertyChangedArgs)
{
var propertyName = propertyChangedArgs.PropertyName;
var run = _textBlock.Inlines.OfType<Run>()
.Where(r => (string) r.GetValue(TargetProperty) == propertyName)
.SingleOrDefault();
if(run == null) return;
var property = sender.GetType().GetProperty(propertyName);
run.Text = (string)property.GetValue(sender, null);
}
}
public static object GetTarget(DependencyObject obj)
{
return obj.GetValue(TargetProperty);
}
public static void SetTarget(DependencyObject obj,
object value)
{
obj.SetValue(TargetProperty, value);
}
public static readonly DependencyProperty TargetProperty =
DependencyProperty.RegisterAttached("Target",
typeof(object),
typeof(BindableRuns),
new PropertyMetadata(null,
TargetPropertyPropertyChanged));
}
I suggest you give the BindableRun a try. I've only used it in WPF, but I don't see why it wouldn't work in Silverlight.