繁体   English   中英

将项目列表框中的选定项目绑定到属性?

[英]Binding Selected Item in a Listbox of Items to a property?

我有一个绑定到货币项目列表的列表框。 货币是一类

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

列表框绑定到货币对象列表,此列表框中的每个项目都是图像和文本块的堆栈面板

我想将SelectedItem属性绑定到Code-behind中的属性,以跟上

<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>

应该位于列表框中所选项目的属性的代码

private Currency sTileCurrency;

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

    }
}

注意:我创建了一个包含XAML内部属性的Class实例。

遵循您所需的MVVM模式(漂亮)

尝试这个:

befor InitializeComponent(); 在您的窗口承包商中添加以下内容:

this.DataContext = this;

所以像这样绑定SelectedItem

SelectedItem="{Binding STileCurrency,Mode=TwoWay}

如果这里有livetilemanager,您应该拥有的工作:

Source={StaticResource livetilemanager}} 

有一个属性:

SCurrencyList

可以? 如果SCurrencyList是隐藏代码中的属性(由于隐藏代码是默认的DataContext),则无需为SelectedItem绑定指定Source。

通过查看绑定错误的方式,可以在调试时关注VS中的“调试窗口”。

顺便说一下,在C#中,通常使用首字母大写来命名属性,例如:

public string Code {get;set;}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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