dotnet / dotnet/wpf

Timing problem in WPF data binding in styles

Open
#9,096 4 comments 1 reaction 0 assignees View on GitHub
Investigate
Dominant language
C#
Stars
7.7k
Forks
1.3k
Avg merge
1d 11h
Merged PRs (30d)
61

Description

### Description

I wanted to have data validation at once in WPF. At the same time I wanted to detect LostFocus, this is the time I modify the DB. Moreover, I needed this in a `DataGrid`. I introduced a temp property. I use the `PropertyChanged` at the `TempName` so the validation happens at once and used the event handler at `LostFocus`. The event handler copied the `TempName` to the `Name` and triggered the DB change. This method worked.

I wanted to use Behavior instead of event handler.

`FinalizeNameCommand` copies the `TempName` to the `Name`. Visual Studio says there is a Binding problem at `FinalizeNameCommand` though the binding works.

![Capture](https://github.com/dotnet/wpf/assets/16515220/e27c4524-fff3-4ab1-8a2e-8a59f71fc63a)

The binding error says the `DataContext` is null, it should be the object behind the selected row, `Person`. `FinalizeNameCommand`
is in that object and it is executed as expected. It seems the Binding is evaulated before the `DataContext` is set, that is why an error is shown. Later the `DataContext` is set and the binding is reevaulated (?), that is why `FinalizeNameCommand` works.

The problem is not only a wrong error message. This causes other problems in the code later.

### Reproduction Steps

https://www.dropbox.com/scl/fi/pugbf1mxo72yjv64sqt8x/ImmediateValidationBindingTest.zip?rlkey=cflx26ayz6kusz3vino1mf90l&dl=0

Download the solution.
Run the program
See the binding error
Modify a name and see that `FinalizeNameCommand` is executed

### Expected behavior

There should be no binding error

### Actual behavior

There is binding error

### Regression?

_No response_

### Known Workarounds

use events instead of behavior

### Impact

_No response_

### Configuration

.net8
windows
x64

### Other information

_No response_

Contributor guide

Open the contributing guide

Research direction

Download and run the linked ImmediateValidationBindingTest solution, then reproduce the binding error in the DataGrid behavior. Start by tracing the binding for FinalizeNameCommand and its DataContext alongside TempName and LostFocus. Done means the command still executes for the selected Person without producing a binding error.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
desktop
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.