开发者

Xaml Binding outside itemtemplate

I would like to bind data of my listbox. Imagine I have something like :

<ListBox ItemsSource="{Binding MyList}"&g开发者_运维问答t;
  <ListBox.ItemTemplate>
    <DataTemplate>
        <TextBlock Text={Binding Value} />
        <TextBlock Text={Binding AbsoluteValue} />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

MyList contains an observable collection of an object that has a property named "Value" AbsoluteValue is a property of the view model, as the MyList property.

Of course, the seconde textbox will have always the same value, but it is what I want :)

How can I tell the binding that the datacontext is not the same for the second textbox ?

Thanks in advance for any help

EDIT : my real sample is a StackPanel. I've tryed

private void StackPanel_Loaded(object sender, RoutedEventArgs e)
{
    StackPanel stackPanel = sender as StackPanel;
    stackPanel.SetBinding(StackPanel.VisibilityProperty, new Binding("Loaded") { Source = DataContext, Mode = BindingMode.TwoWay }); 
}

but it's not working


XAML:

<TextBlock x:Name="tbAbsoluteValue" Loaded="AbsoluteValue_Loaded" />

Codebehind:

void AbsoluteValue_Loaded(object sender, RoutedEventArgs e)
{
    TextBlock absoluteValue = sender as TextBlock;

    absoluteValue.SetBinding(TextBlock.TextProperty, new Binding("AbsoluteValue") { Source = VIEW_MODEL_OBJECT, Mode = BindingMode.TwoWay });
}

That's one way to achieve what you want, you could also use a converter too, or create a StaticResource in your Resources for the VM and bind to that as a source.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜