Textbox Binding to both LostFocus and Property Update

血红的双手。 提交于 2019-12-12 10:48:50

问题


Currently I bind to my TextBoxes as:

Text="{Binding DocValue,
         Mode=TwoWay,
         ValidatesOnDataErrors=True,
         UpdateSourceTrigger=PropertyChanged}"

This works great in getting every keystroke to do button status checking (which I want).

In addition, I would like to track the LostFocus event on the TextBox (through binding) and do some additional calculations that might be too intensive for each keystroke.

Anyone have thoughts on how to accomplish both?


回答1:


Bind a command to the TextBox LostFocus event.

XAML

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

<TextBox Margin="0,287,0,0">
     <i:Interaction.Triggers>
          <i:EventTrigger EventName="LostFocus">
               <i:InvokeCommandAction Command="{Binding LostFocusCommand}" />
          </i:EventTrigger>
     </i:Interaction.Triggers>
</TextBox>

View Model

private ICommand lostFocusCommand;

public ICommand LostFocusCommand
{
    get
    {
        if (lostFocusCommand== null)
        {
            lostFocusCommand= new RelayCommand(param => this.LostTextBoxFocus(), null);
        }
        return lostFocusCommand;
     }
}

private void LostTextBoxFocus()
{
    // do your implementation            
}

you have to reference System.Windows.Interactivity for this. And you have to install a redistributable to use this library. you can download it from here




回答2:


I think I have found a solution... I created a composite command and use that for the additional communication.

Command definition

public static CompositeCommand TextBoxLostFocusCommand = new CompositeCommand();

My textbox

private void TextboxNumeric_LostFocus(object sender, RoutedEventArgs e)
{
    if (Commands.TextBoxLostFocusCommand.RegisteredCommands.Count > 0)
    {
        Commands.TextBoxLostFocusCommand.Execute(null);
    }
}

then in my ViewModel, I create a Delegate Command and wire to it..

It seems like it is working, wonder if there is a better way. One downfall to this is that every Textbox will fire this, not just my items that are attached to formulas I want to calculate. Might need to think of ways to improve on this.



来源:https://stackoverflow.com/questions/15488033/textbox-binding-to-both-lostfocus-and-property-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!