简体   繁体   中英

Binding Selected Item in a Listbox of Items to a property?

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

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}

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, eg:

public string Code {get;set;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM