A Coder
A Coder

Reputation: 3046

TextBlock.Text update ViewModel and CodeBehind WPF

I'm trying to set the Text property of TextBlock both from CodeBehind(xaml.cs) and ViewModel Binding.

In default the values are loaded from ViewModel which works fine.

XAML:

<TextBlock Name="test">
    <TextBlock.Text>
        <MultiBinding StringFormat=" ({0}, {1} of {2})">
            <Binding Path="SeriesId" />
            <Binding Path="SeriesName" />
            <Binding Path="SeriesCalc" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

XAML.cs

In a button click event tried the following,

test.DataContext = "Not Available";

Or

test.Text = "Not Available";

ViewModel:

In another button Command i'm trying to assign the value to the TextBlock.

   SeriesId= GetIds();
   SeriesName= GetNamesWithDE();
   SeriesCalc= CalculateValue();

But once the "Not Available" is set from code behind, it couldn't be overwritten from ViewModel.

Where am i wrong?

Upvotes: 0

Views: 2600

Answers (1)

Vadim Martynov
Vadim Martynov

Reputation: 8892

If you write test.Text = "Not Available"; then you broke data binding by overwriting them with simple string. If you want to complete, use data binding and change TextBlock value from the code behind and you should update binding after that:

test.Text = "Not available";
test.GetBindingExpression(TextBlock.TextProperty).UpdateSource();

or with SetCurrentValue method which sets the value of a dependency property without changing its value source.

test.SetCurrentValue(TextBlock.TextProperty, "Not available");

Upvotes: 4

Related Questions