Search code examples
c#wpfxamldata-binding

How to bind elements in separate xaml files?


I have a MainWindow.xmal which has two TabItems:

<TabItem Header="Config" ... />
<TabItem Header="Results" ... />

I have a separated Config.xaml file for the Config TabItem which has a ListBox:

<ListBox Name="UrlConfig" ... />

I have another separated Results.xaml file for the Results TabItem which has a TaxtBlock:

<TextBlock Name="Url" .../>

The problem is that I'd like to bind the selected value in the ListBox to the TextBlock. How can I do that? Please help :)


Solution

  • I recomend you to work with MVVM, but if not you can implement it with XAML only:

    Use sepparate resource like "Bridge" 'Config' and 'Results'

    Config.xaml:

    <UserControl x:Key="Config">
    <ListBox x:Name="ListBox1" SelectedItem="{Binding Source={StaticResource SelectedValue}, Path=Y, Mode=TwoWay}" >
    <System:String>Minsk</System:String>
    <System:String>London</System:String>
    <System:String>NY</System:String>
    </ListBox>
    </UserControl>
    

    Results.xaml

    <UserControl x:Key="Results">
    <Label Name="Url" Content="{Binding Source={StaticResource SelectedValue}, Path=Y}" />
    </UserControl>
    

    Code of window with TabControl:

    <Window.Resources>
    <!--"Bridge" resource, here will be your own type-->
    <X x:Key="SelectedValue" Y="Minsk"></X>
    </Window.Resources>
    <Grid>
    <TabControl>
    <TabItem Header="Config" Content="{StaticResource ResourceKey=Config}"/>
    <TabItem Header="Results" Content="{StaticResource ResourceKey=Results}"/>
    </TabControl>
    </Grid>