我有一個 JSON,如下圖所示:

我在 ListView 中有一個 ComboBox。我想在 ComboBox 中顯示“對”。
XAML:
<ListView Name="ListPairOption">
<ListView.ItemTemplate>
<DataTemplate x:DataType="data:PairClass">
<StackPanel
x:Name="pilganStack">
<WebView
x:Name="option"
local:MyProperties.HtmlString="{Binding Name}"/>
</StackPanel>
<ComboBox
x:Name="pairOption"
DisplayMemberPath="NameA"
SelectedValue="{Binding ComboBoxClass, Mode=TwoWay}"
ItemsSource="{x:Bind PilihanS}"
PlaceholderText="Pilih" />
</ListView
代碼:
try
{
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonObject questionObject = jsonObject["EXAM_QUESTION"].GetObject();
ObservableCollection<PairClass> itemL = new ObservableCollection<PairClass>();
JsonArray mapArray = questionObject["map"].GetArray();
foreach (JsonValue mapValue in mapArray)
{
JsonArray mapArrayI = mapValue.GetArray();
PairClass pair = new PairClass();
foreach (JsonValue mapValueI in mapArrayI)
{
try
{
string v = mapValueI.ToString();
pair.Name = v;
}
}
}
itemL.Add(pair);
}
JsonArray pairArray = questionObject["pairs"].GetArray();
string pairString = "";
foreach (JsonValue pairValue in pairArray)
{
JsonArray pairArrayI = pairValue.GetArray();
List<ComboBoxClass> PilihanS = new List<ComboBoxClass>();
foreach (JsonValue pairValueI in pairArrayI)
{
try
{
var collection = Regex.Matches(v, "\\\"(.*?)\\\"");
foreach (var item in collection)
{
string v3 = item.ToString().Trim('"');
pairString = v3;
}
}
}
PilihanS.Add(new ComboBoxClass() { NameA = pairString });
}
ListPairOption.ItemsSource = itemL;
}
對類:
public class PairClass
{
public string Name { get; set; }
public ObservableCollection<ComboBoxClass> PilihanS { get; set; }
public PairClass(string name)
{
Name = name;
}
}
public class ComboBoxClass
{
public string NameA { get; set; }
public override string ToString()
{
return this.NameA;
}
}
}
從上面的代碼來看,我在ListView中沒有成功顯示到ComboBox中,導致ComboBox為空,如下圖:
如何將其顯示到ComboBox中?
uj5u.com熱心網友回復:
從上面的代碼來看,我沒有成功將它顯示到ListView中的ComboBox中,使得ComboBox為空,如下圖:
如果要訪問 out 的屬性DataType,請使用Binding ElementName=Control Namethen 訪問來自父級的外部屬性DataContext。請注意,您需要將當前頁面設定DataContext為此this.DataContext = this;。它可以確保您可以PilihanS從DataTemplate.
<ComboBox
x:Name="pairOption"
ItemsSource="{Binding DataContext.PilihanS, ElementName=ListPairOption}"
PlaceholderText="Pilih" />
背后的代碼
public MainPage()
{
this.InitializeComponent();
this.DataContext = this;
}
public List<ComboBoxClass> PilihanS { get; set;} = new List<ComboBoxClass>();
并洗掉上面代碼中的這一行 List<ComboBoxClass> PilihanS = new List<ComboBoxClass>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366632.html
