[英]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.