Search code examples
c#wpfbindingtextbox

WPF - TextBox not binding properly when set to readonly


I have TextBox that I'm using to add (only to add and not read) file path into DB. Text property is set when user selects certain file (OpenFileDialog). So, I set it in readonly state and it won't bind properly. When I remove readonly it works fine.

<Button Name="btnAddFile" Content="+" HorizontalAlignment="Left" Width="23" Height="23" Click="AddFilePath"/>
<TextBox Name="tbxFilePath" Height="23" Text="{Binding FilePath}" Width="364" IsReadOnly="True"/>

When I use:

Text="{Binding FilePath, Mode=OneWayToSource}"

it sometimes work but most of the time it doesn't (?!). I could use TextBlock or Label but I would really like to understand what is going on and use TextBox.

I'm using Entity Framework but don't think it does matter.

Question: How can I programmatically add text to TextBox control which is readonly and be able to bind it.

EDIT: I figured out what the problem is. When I set focus on TextBox after I set it's Text property from code-behind, it works. I guess it has to notify that Text is changed when I do it from code-behind. How to do that?


Solution

  • Have you tried using OneWay Binding?

    MSDN reads:

    OneWay Updates the binding target (target) property when the binding source (source) changes. This type of binding is appropriate if the control being bound is implicitly read-only.

    Which I think covers your scenario.

    The target is your TextBox Text property and your source is your FilePath property on your ViewModel.

    Use:

    Text="{Binding FilePath, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
    

    EDIT

    This answer assumes you have implemented INotifyPropertyChanged on your ViewModel.

    EDIT

    The correct binding mode is OneWayToSource. Confirmed by OP.