-2

having general DataContext taken from class SearchByID there's a need to take a separate DataContext from another class, say, testClass.

XAML example:

<Window.DataContext>
        <model:SearchById />
 </Window.DataContext>

<Grid>

<TextBlock Text="{Binding Description}">
<Texblock.DataContext>
<model: testClass/>
</TextBlock.DataContext>
</TextBlock>


</Grid>

There are no fails, IntelliSens sees all the Properties. But the TextBlock is blank.

any ideas please.

  • It doesn't seem to make sense to assign a testClass instance to the DataContext of a TextBlock, only to show its Description property, which could only be initialized once in the testClass instance. You may perhaps better bind directly to a static property. It is unclear what you are actually trying to achieve. – Clemens Sep 23 '20 at 17:23

1 Answers1

1

One idea, is the Description a property or a field?

A Property will work:

public class TestClass
{
    public string Description { get; set; }
    public TestClass()
    {
        Description = "Test";
    }
}

A field won't:

public class TestClass
{
    public string Description;
    public TestClass()
    {
        Description = "Test";
    }
}

MainWindow.xaml

<TextBlock Text="{Binding Description}"
           Background="Yellow" 
           HorizontalAlignment="Center"
           VerticalAlignment="Center">
    <TextBlock.DataContext>
        <local:TestClass />
    </TextBlock.DataContext>
</TextBlock>

Result: the word test on a white background highlighted yellow

Peter Boone
  • 1,193
  • 1
  • 12
  • 20