Can I use PropertyChanged and LostFocus together?

2019-07-09 20:19发布

问题:

Below is a part of my View code in WPF MVVM structure.

<TextBox Name="VehicalNo_Text" Height="23" Width="80" TextWrapping="Wrap" Text="{Binding VehicleNo, UpdateSourceTrigger=PropertyChanged}"  HorizontalAlignment="Left" />
...                                   
<TextBlock Name="Preview" Text="{Binding EditText, UpdateSourceTrigger=PropertyChanged}"/>
...

I came across a situation where I need to use these both triggers simultaneously.

i.e.

When I update anything in TextBox, I need to show it immediately in my Preview TextBlock. (In ViewModel EditText comes indirectly from VehicleNo itself...), which is already implemented as you can see in code.

And now what I need is when TextBox loose the focus, I need to validate on text.

Is it possible somehow to use this both properties simultaneously?

回答1:

UpdateSourceTrigger=PropertyChanged in TextBlock has no effect

however you can try this way

<TextBox Name="VehicalNo_Text" Height="23" Width="80" TextWrapping="Wrap" 
         Text="{Binding VehicleNo, UpdateSourceTrigger=LostFocus}" 
         HorizontalAlignment="Left" />
...                                   
<TextBlock Name="Preview" Text="{Binding Text, ElementName=VehicalNo_Text}"/>

in above sample we bind the Text property of preview TextBlock to the Text property of TextBox instead of view model property

this will enable you to see a live preview while keeping view model update on lost focus only.

Edit

in order to validate the property you can apply validation rule on TextBox's binding

eg

<TextBox Name="VehicalNo_Text">
    <TextBox.Text>
        <Binding Path="VehicleNo" UpdateSourceTrigger="LostFocus">
            <Binding.ValidationRules>
                <ExceptionValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

you can replace ExceptionValidationRule or add with your own rules.

secondly instead of heaving a calculated property you may perhaps use a converter to display the preview based on VehicleNo's value

eg

<TextBlock Name="Preview" Text="{Binding Text, ElementName=VehicalNo_Text, Converter={StaticResource VehicalNoConverter}}"/>


标签: c# wpf xaml mvvm