gpt4 book ai didi

c# - 绑定(bind)到 UserControl "Failed to assign to property"错误 (Windows 8)

转载 作者:太空狗 更新时间:2023-10-30 00:54:26 25 4
gpt4 key购买 nike

我正在 VS2012 中制作 Windows 8 应用程序,并尝试将对象(卡片)列表绑定(bind)到将显示两个字符串的用户控件。这是我在一个页面上的用户控件代码:

<FlipView x:Name="cardView"/>
<FlipView.ItemTemplate>
<DataTemplate>
<local:TileControl x:Name="cardTile" Width="600" Height="400" QuestionText="{Binding Value.question}" AnswerText="{Binding Value.answer}"/>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>

这是在后面的C#代码中设置的:

cardView.ItemsSource = Storage.content.Decks[currentDeck].Cards;

用户控件“TileControl”控件内部有这些变量:

public string questionTextStr { get; set; }   
public string answerTextStr { get; set; }

public string QuestionText
{
get
{
return questionTextStr;
}
set
{
questionTextStr = value;
questionText.Text = value; //set the textbox content
}
}

public string AnswerText
{
get
{
return answerTextStr;
}
set
{
answerTextStr = value;
answerText.Text = value; //set the textbox content
}
}

错误列表中有一个错误,显示“无法分配给属性‘Flashdeck.TileControl.AnswerText’”。它也适用于问题文本。该应用程序将编译并运行,但是当我打开带有用户控件的页面时崩溃。我做错了什么导致错误和崩溃?谢谢。

编辑:关于套牌和纸牌类的更多信息。甲板:

public class Deck
{
public List<Card> Cards { get; set; }
public bool flagged { get; set; }

public Deck()
{
}

public Deck(List<Card> iCards)
{
Cards = iCards;
flagged = false;
}

public Deck(List<Card> iCards, bool iFlag)
{
Cards = iCards;
flagged = iFlag;
}
}

卡片:

public class Card
{
public string question { get; set; }
public string answer { get; set; }
public bool flagged { get; set; }

public Card()
{
}

public Card(string iQ, string iA)
{
question = iQ;
answer = iA;
flagged = false;
}
}

最佳答案

您的属性必须是 DependencyProperties 才能将值绑定(bind)到它:

public string QuestionText
{
get
{
return (string)GetValue(QuestionTextProperty);
}
set
{
SetValue(QuestionTextProperty, value);
questionText.Text = value; //set the textbox content
}
}
public static DependencyProperty QuestionTextProperty = DependencyProperty.Register("QuestionText", typeof(string), typeof(Deck), new PropertyMetadata(""));

...

为此,您的类 Deck 必须继承自 DependencyObject。

编辑:在您的 Card-Class 中没有名为 Value 的属性,这就是为什么 Binding to Value.question 不起作用,请尝试

<FlipView x:Name="cardView"/>
<FlipView.ItemTemplate>
<DataTemplate>
<local:TileControl x:Name="cardTile" Width="600" Height="400" QuestionText="{Binding Path=question}" AnswerText="{Binding Path=answer}"/>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>

并在问题/答案属性的 setter 中调用 PropertyChanged 事件,如所述here在您的属性值更改时更新绑定(bind)。

关于c# - 绑定(bind)到 UserControl "Failed to assign to property"错误 (Windows 8),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12887858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com