Одно время, когда FK мог бы вызвать Вас проблема, - когда у Вас есть исторические данные, которые ссылаются на ключ (в таблице поиска) даже при том, что Вы больше не хотите доступный ключ.
, Очевидно, решение состоит в том, чтобы разработать вещи лучше впереди, но я думаю о ситуациях с реальным миром здесь, где Вы не всегда имеете контроль над полным решением.
, Например: возможно, Вы взглянули таблица customer_type
, которая перечисляет различные типы клиентов - позволяет, говорят, что необходимо удалить определенный потребительский тип, но (из-за бизнес-ограничений) не в состоянии обновить клиентское программное обеспечение и никого invisaged эта ситуация при разработке программного обеспечения, то, что это - внешний ключ в некоторой другой таблице, может препятствовать тому, чтобы Вы удалили строку даже при том, что Вы знаете исторические данные, что ссылки это не важно.
, будучи записанным с этим несколько раз Вы, вероятно, склоняетесь далеко от осуществления дб отношений.
(я не говорю, это хорошо - просто приведение причины, почему можно решить избежать FKs и ограничений дб в целом)
You're binding too much; you only need to set SelectedValue
and SelectedValuePath
, or SelectedItem
. In this case, it looks like you're actually trying to bind to a specific object. If you're trying to have the ComboBox
set the Category
property on your Book
and the current Book
object actually has a reference to a Category
instance that's in categoryList
, then you should use the SelectedItem
binding and remove the bindings for SelectedValue
and SelectedValuePath
.
Edit
To expand a little on how this is done, SelectedValue
is designed to be used when you have a common piece of information to link your bound item with a property on the list source. For instance, let's say I have a Book
class with a CategoryID
property.
public class Book
{
public string CategoryID { get; set; }
public string Title { get; set; }
}
public class CategoryID
{
public string ID { get; set; }
public string Name { get; set; }
}
In this case, you would do:
<ComboBox SelectedValue = "{Binding CategoryID}"
SelectedValuePath = "ID"
DisplayMemberPath = "Name" />
SelectedItem
, on the other hand, is for when the bound instance has an actual reference to (or, more precisely, an object that is equivalent to) an item in the bound list. So, let's assume the Book
class actually looks like this:
public class Book
{
public Category Category { get; set; }
public string Title { get; set; }
}
In this case, you would do:
<ComboBox SelectedItem = "{Binding Category}"
DisplayMemberPath = "Name" />
But it's very important to note that this will not work unless the Book
class has a reference to the same instance of Category
as you have in the list. If the references are different (even if the values on the classes are equal) then this won't work, as the ComboBox
won't be able to find the Category
referenced in the Book
in the list.
The real problem with the way you were binding it up top (by binding to Category.ID
) is that you're mixing the schemes. You have a reference, but you're trying to bind on the key instead. All this will do is try to set the value on your reference, it will not try to change the reference on your class.
Чтобы описать в коде то, о чем говорит Адам:
<ComboBox
SelectedValuePath="Id"
SelectedItem="{Binding Path=Category}"
ItemsSource="{Binding Source={StaticResource categoryList}}"
DisplayMemberPath="Name" />
, вероятно, более уместно. Обычно лучше рассматривать SelectedValue
как доступный только для чтения и использовать SelectedItem
, чтобы выбрать, какой элемент вы хотите выбрать. Когда вы привязываете SelectedItem
к категории книги
, он все равно автоматически устанавливает для вас свойство SelectedValue
.
Если это все равно не работает, вы может потребоваться проверить, правильно ли работает ваша привязка к Категория
. В частности, добавление DebugConverter
хорошо работает, чтобы гарантировать привязку ожидаемого значения. Как видите, использование DebugConverter
является ответом на этот вопрос.
-Doug