0
votes

I have a listbox which is bound to a list of Currencies items. Currency is a class

public class Currency
{
    public string code { get; set; }
    public string countryName { get; set; }
    public string imgUrl { get; set; }
    public string infoLink { get; set;}  }
}

A list box is bound to a list of Currencies Objects and each item in this listbox is a stackpanel of an image and textblock

I want to bind the SelectedItem property to a property in the Code-behind to keep up

<ListBox Name="sCurrencyLB" Margin="10,0,0,0" Width="Auto" Height="180" 
    IsEnabled="{Binding IsChecked, ElementName=LiveTilesToggleBtn}" 
    SelectedItem="{Binding STileCurrency, Mode=TwoWay, 
            Source={StaticResource livetilemanager}}"  
    ItemsSource="{Binding SCurrencyList}" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="0,10,0,0">
                <TextBlock Name="scountryNametb" Width="50" Text="{Binding code}" 
                    VerticalAlignment="Center" HorizontalAlignment="Right"/>
                <Image Source="{Binding imgUrl}" Height="50" Width="50" 
                    HorizontalAlignment="Left" />
             </StackPanel>
         </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Code of the property that should beind the selected item in the listbox

private Currency sTileCurrency;

public Currency STileCurrency
{
    get
    {
        return appSettings.GetValueorDefault<Currency>("STileCurrency", null);
    }
    set
    {
        if (appSettings.AddOrUpdateValue("STileCurrency", value))
        {
            settings.Save();
        }

    }
}

Note : I created an instance of Class containing the property inside XAML

2

2 Answers

0
votes

Follow MVVM Pattern(pretty) that's what you need

try this:

befor InitializeComponent(); in your contractor of window add this:

this.DataContext = this;

so bind the SelectedItem like this

SelectedItem="{Binding STileCurrency,Mode=TwoWay}
0
votes

What you have should work if livetilemanager here:

Source={StaticResource livetilemanager}} 

Has a property on it:

SCurrencyList

Does it? If SCurrencyList is a property in your code-behind - since the code-behind is the default DataContext - you do not need to specify a Source for you SelectedItem binding.

By the way to see binding errors keep an eye on the Debug Window in VS while debugging.

Incidentally in C# it typical to name properties with capital first letter, e.g.:

public string Code {get;set;}