Sunday, May 1, 2011

Handling Content property in WPF

I'm currently facing huge problem i.e I'm showing Image and some text in a image the problem is when I change content property of button from code, my image disappears and only assigned text is shown, I wan to retain image and just wann change the text, Any suggetions how to handle it

<Button x:Name="btnPrescan" Margin="8" Grid.Column="2" Click="btnPrescan_Click">
    <StackPanel Orientation="Horizontal">
         <Image Source="Icons\Scan_Start_Icon.png" Height="14" Width="23"/>
         <TextBlock x:Name="tbButtonText"  Text="    Prescan"/>
    </StackPanel>
</Button>

and button looks something like this

alt text

Thanks

From stackoverflow
  • You should do this way,

    ((TextBlock)btnPrescan.GetTemplatedChild("tbButtonText")).Text = "Your Text"
    
  • Bind the text to a backing property on your UserControl:

    <Button x:Name="btnPrescan" Margin="8" Grid.Column="2" Click="btnPrescan_Click">
        <StackPanel Orientation="Horizontal">
             <Image Source="Icons\Scan_Start_Icon.png" Height="14" Width="23"/>
             <!-- assumes DataContext is set appropriately -->
             <TextBlock Text="{Binding ButtonText}"/>
        </StackPanel>
    </Button>
    

    Then just change the backing property:

    this.ButtonText = "New button text";
    

    HTH, Kent

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.