bind a ComboboxItem as a checkbox to its presence in a list?











up vote
-1
down vote

favorite












I am new to wpf and aside from the reading of 'WPF unleashed', I try to write a little program, it gives me a direction to go to.
So here is my problem : I want to manage my books, at home, with a little library program. Each book is stored in a Book class instance. thus, This Book class contains all the informations of the book, and among them its keywords, which is a ObservableCollection in a 'Keywords' property:



public ObservableCollection<string> Keywords
{
get => _keywords;
set
{
_keywords = value;
OnPropertyChanged("Keywords");
}
}


(_keywords is a string).



What I want is to display a textBox and a combobox which show related piece of informations: the textBox show all the Keywords of the selected book, and the combobox show a list of checkboxes, it is filled by the list of all the Keywords in all the books of the library, listed once (duplicate removed) and each checkbox is checked if the keyword is present in the listbox of the selected book.
I will try to explain it differently : each book contains a list of all its keywords. The combobox contains all the existing keywords (of all the books) and those related to the selected book are checked : it allows me 2 ways to add/edit/remove keywords : with the textbox, or by checking/unchecking the checkBoxes.



Back to my problem : how can I code this, using a maximum of databinding?
For the textbox, I see no problem : I will create a property in 'Book' say 'KeywordsForTextbox' with only a getter returning the keywords collection items merged with the appropriate separation character. then, using a dataContext pointed to the selectedBook, the text property of the textbox is bound to KeywordsForTextbox.
I would rather not considering the textbox edition for now.



But for the combobox, there are 2 things to bind:
1/ the list of all the keywords. I can put in my BookManagement class (which ... manages the Book class) a property whose getter will return the list of all the keywords (via link).
2/ each ComboboxItem will be edited in XAML but how to implement the behavior of setting it as checked/unchecked if the given keyword(got by using the property ItemSource of the checkbox to the Keyword property of the Book instance) is contained in the selectedItem.Keywords ?



more shortly : how to bind the checked property of a CheckBoxItem to the presence of this string in listView's selectedItem.Keywords (a list of strings)?



I apologize for the messy aspect of my question!



thank you.



EDIT



Well, I managed to write all the stuff, it builds and run, but there is a problem; in fact in the combobox, the itemsSource was written like this:



ItemsSource="{Binding Source={StaticResource AllBooks}}"


and AllBooks is a resource:



<ObjectDataProvider
x:Key="AllBooks"
MethodName="listOfAllKeywords"
ObjectType="{x:Type mangmt:BookManagement}" />


here is the method:



public static ObservableCollection<string> listOfAllKeywords()
{
if (App.Books != null)
{

IEnumerable<string> kws = App.Books.SelectMany(book => book.Keywords).Distinct();
return new ObservableCollection<string>(kws);

}
else return new ObservableCollection<string>();


}


When I run my program, the window is displayed normally, but if I click on a book to display it, and if I click on the combobox, at the second click I get an exception :
System.InvalidCastException : 'Impossible d'effectuer un cast d'un objet de type 'MS.Internal.NamedObject' en type 'System.String'.'
which saying the cast is impossible.
I saw in the debugging that in the multibinding, the seconf parameter is null(anyway it seems not very relevant because the exception is caused by the first parameter, but yet it's annoying).



I recall you my multibinding:



<ComboBox
x:Name="cbb_Keywords"
Grid.Column="2"
Width="300"
Margin="5,0,0,0"
HorizontalAlignment="Left"
ItemsSource="{Binding Source={StaticResource AllBooks}}"
DataContext="{Binding ElementName=listBoxBooks,Path=SelectedItem,Mode=TwoWay}">

<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Width="200">
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}" >
<Binding Path="KeywordsForTextbox"></Binding>
<Binding RelativeSource="{RelativeSource Self}" Path="Content"></Binding>
</MultiBinding>
</CheckBox>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>


here is KeywordsForTextBox:



public string KeywordsForTextbox
{
get { return string.Join(",", _keywords); }

}


(it's in the Book class)
is the first binding (of the multibinding) wrong?why?



thank you.



EDIT 2
I created a new post because this one is too messy(too much text in my question) and the area of the possible causes is much restricted as I saw this was a dependencyProperty problem. here is the link : here in stack overflow










share|improve this question
























  • Only thing I can think of trying is multibinding the IsChecked property of the CheckBox to the KeyWordsForTextbox and the CheckBox's content and using an IMultiValueConverter to split the string and check if the content string appears in the list in order to return 'True'.
    – Simon Evans
    Nov 9 at 20:41















up vote
-1
down vote

favorite












I am new to wpf and aside from the reading of 'WPF unleashed', I try to write a little program, it gives me a direction to go to.
So here is my problem : I want to manage my books, at home, with a little library program. Each book is stored in a Book class instance. thus, This Book class contains all the informations of the book, and among them its keywords, which is a ObservableCollection in a 'Keywords' property:



public ObservableCollection<string> Keywords
{
get => _keywords;
set
{
_keywords = value;
OnPropertyChanged("Keywords");
}
}


(_keywords is a string).



What I want is to display a textBox and a combobox which show related piece of informations: the textBox show all the Keywords of the selected book, and the combobox show a list of checkboxes, it is filled by the list of all the Keywords in all the books of the library, listed once (duplicate removed) and each checkbox is checked if the keyword is present in the listbox of the selected book.
I will try to explain it differently : each book contains a list of all its keywords. The combobox contains all the existing keywords (of all the books) and those related to the selected book are checked : it allows me 2 ways to add/edit/remove keywords : with the textbox, or by checking/unchecking the checkBoxes.



Back to my problem : how can I code this, using a maximum of databinding?
For the textbox, I see no problem : I will create a property in 'Book' say 'KeywordsForTextbox' with only a getter returning the keywords collection items merged with the appropriate separation character. then, using a dataContext pointed to the selectedBook, the text property of the textbox is bound to KeywordsForTextbox.
I would rather not considering the textbox edition for now.



But for the combobox, there are 2 things to bind:
1/ the list of all the keywords. I can put in my BookManagement class (which ... manages the Book class) a property whose getter will return the list of all the keywords (via link).
2/ each ComboboxItem will be edited in XAML but how to implement the behavior of setting it as checked/unchecked if the given keyword(got by using the property ItemSource of the checkbox to the Keyword property of the Book instance) is contained in the selectedItem.Keywords ?



more shortly : how to bind the checked property of a CheckBoxItem to the presence of this string in listView's selectedItem.Keywords (a list of strings)?



I apologize for the messy aspect of my question!



thank you.



EDIT



Well, I managed to write all the stuff, it builds and run, but there is a problem; in fact in the combobox, the itemsSource was written like this:



ItemsSource="{Binding Source={StaticResource AllBooks}}"


and AllBooks is a resource:



<ObjectDataProvider
x:Key="AllBooks"
MethodName="listOfAllKeywords"
ObjectType="{x:Type mangmt:BookManagement}" />


here is the method:



public static ObservableCollection<string> listOfAllKeywords()
{
if (App.Books != null)
{

IEnumerable<string> kws = App.Books.SelectMany(book => book.Keywords).Distinct();
return new ObservableCollection<string>(kws);

}
else return new ObservableCollection<string>();


}


When I run my program, the window is displayed normally, but if I click on a book to display it, and if I click on the combobox, at the second click I get an exception :
System.InvalidCastException : 'Impossible d'effectuer un cast d'un objet de type 'MS.Internal.NamedObject' en type 'System.String'.'
which saying the cast is impossible.
I saw in the debugging that in the multibinding, the seconf parameter is null(anyway it seems not very relevant because the exception is caused by the first parameter, but yet it's annoying).



I recall you my multibinding:



<ComboBox
x:Name="cbb_Keywords"
Grid.Column="2"
Width="300"
Margin="5,0,0,0"
HorizontalAlignment="Left"
ItemsSource="{Binding Source={StaticResource AllBooks}}"
DataContext="{Binding ElementName=listBoxBooks,Path=SelectedItem,Mode=TwoWay}">

<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Width="200">
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}" >
<Binding Path="KeywordsForTextbox"></Binding>
<Binding RelativeSource="{RelativeSource Self}" Path="Content"></Binding>
</MultiBinding>
</CheckBox>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>


here is KeywordsForTextBox:



public string KeywordsForTextbox
{
get { return string.Join(",", _keywords); }

}


(it's in the Book class)
is the first binding (of the multibinding) wrong?why?



thank you.



EDIT 2
I created a new post because this one is too messy(too much text in my question) and the area of the possible causes is much restricted as I saw this was a dependencyProperty problem. here is the link : here in stack overflow










share|improve this question
























  • Only thing I can think of trying is multibinding the IsChecked property of the CheckBox to the KeyWordsForTextbox and the CheckBox's content and using an IMultiValueConverter to split the string and check if the content string appears in the list in order to return 'True'.
    – Simon Evans
    Nov 9 at 20:41













up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











I am new to wpf and aside from the reading of 'WPF unleashed', I try to write a little program, it gives me a direction to go to.
So here is my problem : I want to manage my books, at home, with a little library program. Each book is stored in a Book class instance. thus, This Book class contains all the informations of the book, and among them its keywords, which is a ObservableCollection in a 'Keywords' property:



public ObservableCollection<string> Keywords
{
get => _keywords;
set
{
_keywords = value;
OnPropertyChanged("Keywords");
}
}


(_keywords is a string).



What I want is to display a textBox and a combobox which show related piece of informations: the textBox show all the Keywords of the selected book, and the combobox show a list of checkboxes, it is filled by the list of all the Keywords in all the books of the library, listed once (duplicate removed) and each checkbox is checked if the keyword is present in the listbox of the selected book.
I will try to explain it differently : each book contains a list of all its keywords. The combobox contains all the existing keywords (of all the books) and those related to the selected book are checked : it allows me 2 ways to add/edit/remove keywords : with the textbox, or by checking/unchecking the checkBoxes.



Back to my problem : how can I code this, using a maximum of databinding?
For the textbox, I see no problem : I will create a property in 'Book' say 'KeywordsForTextbox' with only a getter returning the keywords collection items merged with the appropriate separation character. then, using a dataContext pointed to the selectedBook, the text property of the textbox is bound to KeywordsForTextbox.
I would rather not considering the textbox edition for now.



But for the combobox, there are 2 things to bind:
1/ the list of all the keywords. I can put in my BookManagement class (which ... manages the Book class) a property whose getter will return the list of all the keywords (via link).
2/ each ComboboxItem will be edited in XAML but how to implement the behavior of setting it as checked/unchecked if the given keyword(got by using the property ItemSource of the checkbox to the Keyword property of the Book instance) is contained in the selectedItem.Keywords ?



more shortly : how to bind the checked property of a CheckBoxItem to the presence of this string in listView's selectedItem.Keywords (a list of strings)?



I apologize for the messy aspect of my question!



thank you.



EDIT



Well, I managed to write all the stuff, it builds and run, but there is a problem; in fact in the combobox, the itemsSource was written like this:



ItemsSource="{Binding Source={StaticResource AllBooks}}"


and AllBooks is a resource:



<ObjectDataProvider
x:Key="AllBooks"
MethodName="listOfAllKeywords"
ObjectType="{x:Type mangmt:BookManagement}" />


here is the method:



public static ObservableCollection<string> listOfAllKeywords()
{
if (App.Books != null)
{

IEnumerable<string> kws = App.Books.SelectMany(book => book.Keywords).Distinct();
return new ObservableCollection<string>(kws);

}
else return new ObservableCollection<string>();


}


When I run my program, the window is displayed normally, but if I click on a book to display it, and if I click on the combobox, at the second click I get an exception :
System.InvalidCastException : 'Impossible d'effectuer un cast d'un objet de type 'MS.Internal.NamedObject' en type 'System.String'.'
which saying the cast is impossible.
I saw in the debugging that in the multibinding, the seconf parameter is null(anyway it seems not very relevant because the exception is caused by the first parameter, but yet it's annoying).



I recall you my multibinding:



<ComboBox
x:Name="cbb_Keywords"
Grid.Column="2"
Width="300"
Margin="5,0,0,0"
HorizontalAlignment="Left"
ItemsSource="{Binding Source={StaticResource AllBooks}}"
DataContext="{Binding ElementName=listBoxBooks,Path=SelectedItem,Mode=TwoWay}">

<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Width="200">
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}" >
<Binding Path="KeywordsForTextbox"></Binding>
<Binding RelativeSource="{RelativeSource Self}" Path="Content"></Binding>
</MultiBinding>
</CheckBox>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>


here is KeywordsForTextBox:



public string KeywordsForTextbox
{
get { return string.Join(",", _keywords); }

}


(it's in the Book class)
is the first binding (of the multibinding) wrong?why?



thank you.



EDIT 2
I created a new post because this one is too messy(too much text in my question) and the area of the possible causes is much restricted as I saw this was a dependencyProperty problem. here is the link : here in stack overflow










share|improve this question















I am new to wpf and aside from the reading of 'WPF unleashed', I try to write a little program, it gives me a direction to go to.
So here is my problem : I want to manage my books, at home, with a little library program. Each book is stored in a Book class instance. thus, This Book class contains all the informations of the book, and among them its keywords, which is a ObservableCollection in a 'Keywords' property:



public ObservableCollection<string> Keywords
{
get => _keywords;
set
{
_keywords = value;
OnPropertyChanged("Keywords");
}
}


(_keywords is a string).



What I want is to display a textBox and a combobox which show related piece of informations: the textBox show all the Keywords of the selected book, and the combobox show a list of checkboxes, it is filled by the list of all the Keywords in all the books of the library, listed once (duplicate removed) and each checkbox is checked if the keyword is present in the listbox of the selected book.
I will try to explain it differently : each book contains a list of all its keywords. The combobox contains all the existing keywords (of all the books) and those related to the selected book are checked : it allows me 2 ways to add/edit/remove keywords : with the textbox, or by checking/unchecking the checkBoxes.



Back to my problem : how can I code this, using a maximum of databinding?
For the textbox, I see no problem : I will create a property in 'Book' say 'KeywordsForTextbox' with only a getter returning the keywords collection items merged with the appropriate separation character. then, using a dataContext pointed to the selectedBook, the text property of the textbox is bound to KeywordsForTextbox.
I would rather not considering the textbox edition for now.



But for the combobox, there are 2 things to bind:
1/ the list of all the keywords. I can put in my BookManagement class (which ... manages the Book class) a property whose getter will return the list of all the keywords (via link).
2/ each ComboboxItem will be edited in XAML but how to implement the behavior of setting it as checked/unchecked if the given keyword(got by using the property ItemSource of the checkbox to the Keyword property of the Book instance) is contained in the selectedItem.Keywords ?



more shortly : how to bind the checked property of a CheckBoxItem to the presence of this string in listView's selectedItem.Keywords (a list of strings)?



I apologize for the messy aspect of my question!



thank you.



EDIT



Well, I managed to write all the stuff, it builds and run, but there is a problem; in fact in the combobox, the itemsSource was written like this:



ItemsSource="{Binding Source={StaticResource AllBooks}}"


and AllBooks is a resource:



<ObjectDataProvider
x:Key="AllBooks"
MethodName="listOfAllKeywords"
ObjectType="{x:Type mangmt:BookManagement}" />


here is the method:



public static ObservableCollection<string> listOfAllKeywords()
{
if (App.Books != null)
{

IEnumerable<string> kws = App.Books.SelectMany(book => book.Keywords).Distinct();
return new ObservableCollection<string>(kws);

}
else return new ObservableCollection<string>();


}


When I run my program, the window is displayed normally, but if I click on a book to display it, and if I click on the combobox, at the second click I get an exception :
System.InvalidCastException : 'Impossible d'effectuer un cast d'un objet de type 'MS.Internal.NamedObject' en type 'System.String'.'
which saying the cast is impossible.
I saw in the debugging that in the multibinding, the seconf parameter is null(anyway it seems not very relevant because the exception is caused by the first parameter, but yet it's annoying).



I recall you my multibinding:



<ComboBox
x:Name="cbb_Keywords"
Grid.Column="2"
Width="300"
Margin="5,0,0,0"
HorizontalAlignment="Left"
ItemsSource="{Binding Source={StaticResource AllBooks}}"
DataContext="{Binding ElementName=listBoxBooks,Path=SelectedItem,Mode=TwoWay}">

<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Width="200">
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}" >
<Binding Path="KeywordsForTextbox"></Binding>
<Binding RelativeSource="{RelativeSource Self}" Path="Content"></Binding>
</MultiBinding>
</CheckBox>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>


here is KeywordsForTextBox:



public string KeywordsForTextbox
{
get { return string.Join(",", _keywords); }

}


(it's in the Book class)
is the first binding (of the multibinding) wrong?why?



thank you.



EDIT 2
I created a new post because this one is too messy(too much text in my question) and the area of the possible causes is much restricted as I saw this was a dependencyProperty problem. here is the link : here in stack overflow







c# wpf checkbox data-binding






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 13:55

























asked Nov 9 at 19:22









lolveley

7091922




7091922












  • Only thing I can think of trying is multibinding the IsChecked property of the CheckBox to the KeyWordsForTextbox and the CheckBox's content and using an IMultiValueConverter to split the string and check if the content string appears in the list in order to return 'True'.
    – Simon Evans
    Nov 9 at 20:41


















  • Only thing I can think of trying is multibinding the IsChecked property of the CheckBox to the KeyWordsForTextbox and the CheckBox's content and using an IMultiValueConverter to split the string and check if the content string appears in the list in order to return 'True'.
    – Simon Evans
    Nov 9 at 20:41
















Only thing I can think of trying is multibinding the IsChecked property of the CheckBox to the KeyWordsForTextbox and the CheckBox's content and using an IMultiValueConverter to split the string and check if the content string appears in the list in order to return 'True'.
– Simon Evans
Nov 9 at 20:41




Only thing I can think of trying is multibinding the IsChecked property of the CheckBox to the KeyWordsForTextbox and the CheckBox's content and using an IMultiValueConverter to split the string and check if the content string appears in the list in order to return 'True'.
– Simon Evans
Nov 9 at 20:41












1 Answer
1






active

oldest

votes

















up vote
1
down vote













based on my suggestion in the comment, IMultiValueConverter (Sorry in VB):



Public Class TextInListTrueFalseConverter
Implements IMultiValueConverter

Public Function Convert(values() As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert
Dim Checked As Boolean = False
If Not values Is Nothing Then
If values.Count = 2 Then
Dim ListString As String = values(0)
Dim WordToFind As String = values(1)
If Not ListString Is Nothing Then
Dim KeywordList As List(Of String) = ListString.Split(";").ToList 'Assuming you seperator is a ;
If KeywordList.Contains(WordToFind) Then Checked = True
End If
End If
End If
Return Checked
End Function

Public Function ConvertBack(value As Object, targetTypes() As Type, parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack
Throw New NotImplementedException()
End Function
End Class


XAML:



<CheckBox >
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}">
<Binding Path="KeywordsForTextbox" />
<Binding RelativeSource="{RelativeSource Self}" Path="Content" />
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>


(use DataContext of the Combo to bind to the Book class, and use ItemsSource to load the KeyWords)



Finally, add <Local:TextInListTrueFalseConverter x:Key="TextInListTrueFalseConverter" /> as a resource, adding the "Local" namespace if not already present.e.g. xmlns:Local="clr-namespace:APPNAME".



Not tested, but think it should work, or at least give you something to go on.



EDIT



My bad. I had it in my head that the ComboBoxItems would Inherit the DataContext from the ComboBox, but of course they do not - they are bound to the ItemsSource obviously. Try the following changes, I have updated the first Binding to be to the ListBox of Books. I have also added in the <CheckBox.IsChecked> where appropriate, and also added Content="{Binding}" to the CheckBox:



                    <ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Width="200" Content={Binding}>
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}" >
<Binding ElementName=listBoxBooks, Path=SelectedItem.KeywordsForTextbox"></Binding>
<Binding RelativeSource="{RelativeSource Self}" Path="Content"></Binding>
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>


You may also wish to add some validation to the IMultiValueConverter to make sure the passed values are not unset, to avoid an exception: If Not values(0) Is DependencyProperty.UnsetValue And Not values(1) Is DependencyProperty.UnsetValue Then in VB.






share|improve this answer























  • I will try and post here the results, it could take some time ! Thank you
    – lolveley
    Nov 9 at 21:19










  • No worries - just edited the XAML as noticed an error. I'll also mention that the xceed WPF Toolkit (free version) includes a CheckComboBox, which you may want to consider (if you're not already using it). Save reinventing the wheel.
    – Simon Evans
    Nov 9 at 21:40










  • 2 comments about my edit : a pair of tags was missing (<checkbox. isChecked> and its closing sibling) and the first value, value[0], was unset. I think the initialization has problems but I can't figure out where.
    – lolveley
    Nov 10 at 12:29










  • for the provided component : now that I spent a lot of time to make it work, with your aid, I am avid to succeed in completing the job !
    – lolveley
    Nov 10 at 12:33










  • I have suggested some edits in the answer.
    – Simon Evans
    Nov 10 at 14:00











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53232081%2fbind-a-comboboxitem-as-a-checkbox-to-its-presence-in-a-list%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote













based on my suggestion in the comment, IMultiValueConverter (Sorry in VB):



Public Class TextInListTrueFalseConverter
Implements IMultiValueConverter

Public Function Convert(values() As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert
Dim Checked As Boolean = False
If Not values Is Nothing Then
If values.Count = 2 Then
Dim ListString As String = values(0)
Dim WordToFind As String = values(1)
If Not ListString Is Nothing Then
Dim KeywordList As List(Of String) = ListString.Split(";").ToList 'Assuming you seperator is a ;
If KeywordList.Contains(WordToFind) Then Checked = True
End If
End If
End If
Return Checked
End Function

Public Function ConvertBack(value As Object, targetTypes() As Type, parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack
Throw New NotImplementedException()
End Function
End Class


XAML:



<CheckBox >
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}">
<Binding Path="KeywordsForTextbox" />
<Binding RelativeSource="{RelativeSource Self}" Path="Content" />
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>


(use DataContext of the Combo to bind to the Book class, and use ItemsSource to load the KeyWords)



Finally, add <Local:TextInListTrueFalseConverter x:Key="TextInListTrueFalseConverter" /> as a resource, adding the "Local" namespace if not already present.e.g. xmlns:Local="clr-namespace:APPNAME".



Not tested, but think it should work, or at least give you something to go on.



EDIT



My bad. I had it in my head that the ComboBoxItems would Inherit the DataContext from the ComboBox, but of course they do not - they are bound to the ItemsSource obviously. Try the following changes, I have updated the first Binding to be to the ListBox of Books. I have also added in the <CheckBox.IsChecked> where appropriate, and also added Content="{Binding}" to the CheckBox:



                    <ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Width="200" Content={Binding}>
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}" >
<Binding ElementName=listBoxBooks, Path=SelectedItem.KeywordsForTextbox"></Binding>
<Binding RelativeSource="{RelativeSource Self}" Path="Content"></Binding>
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>


You may also wish to add some validation to the IMultiValueConverter to make sure the passed values are not unset, to avoid an exception: If Not values(0) Is DependencyProperty.UnsetValue And Not values(1) Is DependencyProperty.UnsetValue Then in VB.






share|improve this answer























  • I will try and post here the results, it could take some time ! Thank you
    – lolveley
    Nov 9 at 21:19










  • No worries - just edited the XAML as noticed an error. I'll also mention that the xceed WPF Toolkit (free version) includes a CheckComboBox, which you may want to consider (if you're not already using it). Save reinventing the wheel.
    – Simon Evans
    Nov 9 at 21:40










  • 2 comments about my edit : a pair of tags was missing (<checkbox. isChecked> and its closing sibling) and the first value, value[0], was unset. I think the initialization has problems but I can't figure out where.
    – lolveley
    Nov 10 at 12:29










  • for the provided component : now that I spent a lot of time to make it work, with your aid, I am avid to succeed in completing the job !
    – lolveley
    Nov 10 at 12:33










  • I have suggested some edits in the answer.
    – Simon Evans
    Nov 10 at 14:00















up vote
1
down vote













based on my suggestion in the comment, IMultiValueConverter (Sorry in VB):



Public Class TextInListTrueFalseConverter
Implements IMultiValueConverter

Public Function Convert(values() As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert
Dim Checked As Boolean = False
If Not values Is Nothing Then
If values.Count = 2 Then
Dim ListString As String = values(0)
Dim WordToFind As String = values(1)
If Not ListString Is Nothing Then
Dim KeywordList As List(Of String) = ListString.Split(";").ToList 'Assuming you seperator is a ;
If KeywordList.Contains(WordToFind) Then Checked = True
End If
End If
End If
Return Checked
End Function

Public Function ConvertBack(value As Object, targetTypes() As Type, parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack
Throw New NotImplementedException()
End Function
End Class


XAML:



<CheckBox >
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}">
<Binding Path="KeywordsForTextbox" />
<Binding RelativeSource="{RelativeSource Self}" Path="Content" />
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>


(use DataContext of the Combo to bind to the Book class, and use ItemsSource to load the KeyWords)



Finally, add <Local:TextInListTrueFalseConverter x:Key="TextInListTrueFalseConverter" /> as a resource, adding the "Local" namespace if not already present.e.g. xmlns:Local="clr-namespace:APPNAME".



Not tested, but think it should work, or at least give you something to go on.



EDIT



My bad. I had it in my head that the ComboBoxItems would Inherit the DataContext from the ComboBox, but of course they do not - they are bound to the ItemsSource obviously. Try the following changes, I have updated the first Binding to be to the ListBox of Books. I have also added in the <CheckBox.IsChecked> where appropriate, and also added Content="{Binding}" to the CheckBox:



                    <ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Width="200" Content={Binding}>
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}" >
<Binding ElementName=listBoxBooks, Path=SelectedItem.KeywordsForTextbox"></Binding>
<Binding RelativeSource="{RelativeSource Self}" Path="Content"></Binding>
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>


You may also wish to add some validation to the IMultiValueConverter to make sure the passed values are not unset, to avoid an exception: If Not values(0) Is DependencyProperty.UnsetValue And Not values(1) Is DependencyProperty.UnsetValue Then in VB.






share|improve this answer























  • I will try and post here the results, it could take some time ! Thank you
    – lolveley
    Nov 9 at 21:19










  • No worries - just edited the XAML as noticed an error. I'll also mention that the xceed WPF Toolkit (free version) includes a CheckComboBox, which you may want to consider (if you're not already using it). Save reinventing the wheel.
    – Simon Evans
    Nov 9 at 21:40










  • 2 comments about my edit : a pair of tags was missing (<checkbox. isChecked> and its closing sibling) and the first value, value[0], was unset. I think the initialization has problems but I can't figure out where.
    – lolveley
    Nov 10 at 12:29










  • for the provided component : now that I spent a lot of time to make it work, with your aid, I am avid to succeed in completing the job !
    – lolveley
    Nov 10 at 12:33










  • I have suggested some edits in the answer.
    – Simon Evans
    Nov 10 at 14:00













up vote
1
down vote










up vote
1
down vote









based on my suggestion in the comment, IMultiValueConverter (Sorry in VB):



Public Class TextInListTrueFalseConverter
Implements IMultiValueConverter

Public Function Convert(values() As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert
Dim Checked As Boolean = False
If Not values Is Nothing Then
If values.Count = 2 Then
Dim ListString As String = values(0)
Dim WordToFind As String = values(1)
If Not ListString Is Nothing Then
Dim KeywordList As List(Of String) = ListString.Split(";").ToList 'Assuming you seperator is a ;
If KeywordList.Contains(WordToFind) Then Checked = True
End If
End If
End If
Return Checked
End Function

Public Function ConvertBack(value As Object, targetTypes() As Type, parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack
Throw New NotImplementedException()
End Function
End Class


XAML:



<CheckBox >
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}">
<Binding Path="KeywordsForTextbox" />
<Binding RelativeSource="{RelativeSource Self}" Path="Content" />
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>


(use DataContext of the Combo to bind to the Book class, and use ItemsSource to load the KeyWords)



Finally, add <Local:TextInListTrueFalseConverter x:Key="TextInListTrueFalseConverter" /> as a resource, adding the "Local" namespace if not already present.e.g. xmlns:Local="clr-namespace:APPNAME".



Not tested, but think it should work, or at least give you something to go on.



EDIT



My bad. I had it in my head that the ComboBoxItems would Inherit the DataContext from the ComboBox, but of course they do not - they are bound to the ItemsSource obviously. Try the following changes, I have updated the first Binding to be to the ListBox of Books. I have also added in the <CheckBox.IsChecked> where appropriate, and also added Content="{Binding}" to the CheckBox:



                    <ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Width="200" Content={Binding}>
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}" >
<Binding ElementName=listBoxBooks, Path=SelectedItem.KeywordsForTextbox"></Binding>
<Binding RelativeSource="{RelativeSource Self}" Path="Content"></Binding>
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>


You may also wish to add some validation to the IMultiValueConverter to make sure the passed values are not unset, to avoid an exception: If Not values(0) Is DependencyProperty.UnsetValue And Not values(1) Is DependencyProperty.UnsetValue Then in VB.






share|improve this answer














based on my suggestion in the comment, IMultiValueConverter (Sorry in VB):



Public Class TextInListTrueFalseConverter
Implements IMultiValueConverter

Public Function Convert(values() As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert
Dim Checked As Boolean = False
If Not values Is Nothing Then
If values.Count = 2 Then
Dim ListString As String = values(0)
Dim WordToFind As String = values(1)
If Not ListString Is Nothing Then
Dim KeywordList As List(Of String) = ListString.Split(";").ToList 'Assuming you seperator is a ;
If KeywordList.Contains(WordToFind) Then Checked = True
End If
End If
End If
Return Checked
End Function

Public Function ConvertBack(value As Object, targetTypes() As Type, parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack
Throw New NotImplementedException()
End Function
End Class


XAML:



<CheckBox >
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}">
<Binding Path="KeywordsForTextbox" />
<Binding RelativeSource="{RelativeSource Self}" Path="Content" />
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>


(use DataContext of the Combo to bind to the Book class, and use ItemsSource to load the KeyWords)



Finally, add <Local:TextInListTrueFalseConverter x:Key="TextInListTrueFalseConverter" /> as a resource, adding the "Local" namespace if not already present.e.g. xmlns:Local="clr-namespace:APPNAME".



Not tested, but think it should work, or at least give you something to go on.



EDIT



My bad. I had it in my head that the ComboBoxItems would Inherit the DataContext from the ComboBox, but of course they do not - they are bound to the ItemsSource obviously. Try the following changes, I have updated the first Binding to be to the ListBox of Books. I have also added in the <CheckBox.IsChecked> where appropriate, and also added Content="{Binding}" to the CheckBox:



                    <ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Width="200" Content={Binding}>
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource TextInListTrueFalseConverter}" >
<Binding ElementName=listBoxBooks, Path=SelectedItem.KeywordsForTextbox"></Binding>
<Binding RelativeSource="{RelativeSource Self}" Path="Content"></Binding>
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>


You may also wish to add some validation to the IMultiValueConverter to make sure the passed values are not unset, to avoid an exception: If Not values(0) Is DependencyProperty.UnsetValue And Not values(1) Is DependencyProperty.UnsetValue Then in VB.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 10 at 15:47

























answered Nov 9 at 21:13









Simon Evans

11617




11617












  • I will try and post here the results, it could take some time ! Thank you
    – lolveley
    Nov 9 at 21:19










  • No worries - just edited the XAML as noticed an error. I'll also mention that the xceed WPF Toolkit (free version) includes a CheckComboBox, which you may want to consider (if you're not already using it). Save reinventing the wheel.
    – Simon Evans
    Nov 9 at 21:40










  • 2 comments about my edit : a pair of tags was missing (<checkbox. isChecked> and its closing sibling) and the first value, value[0], was unset. I think the initialization has problems but I can't figure out where.
    – lolveley
    Nov 10 at 12:29










  • for the provided component : now that I spent a lot of time to make it work, with your aid, I am avid to succeed in completing the job !
    – lolveley
    Nov 10 at 12:33










  • I have suggested some edits in the answer.
    – Simon Evans
    Nov 10 at 14:00


















  • I will try and post here the results, it could take some time ! Thank you
    – lolveley
    Nov 9 at 21:19










  • No worries - just edited the XAML as noticed an error. I'll also mention that the xceed WPF Toolkit (free version) includes a CheckComboBox, which you may want to consider (if you're not already using it). Save reinventing the wheel.
    – Simon Evans
    Nov 9 at 21:40










  • 2 comments about my edit : a pair of tags was missing (<checkbox. isChecked> and its closing sibling) and the first value, value[0], was unset. I think the initialization has problems but I can't figure out where.
    – lolveley
    Nov 10 at 12:29










  • for the provided component : now that I spent a lot of time to make it work, with your aid, I am avid to succeed in completing the job !
    – lolveley
    Nov 10 at 12:33










  • I have suggested some edits in the answer.
    – Simon Evans
    Nov 10 at 14:00
















I will try and post here the results, it could take some time ! Thank you
– lolveley
Nov 9 at 21:19




I will try and post here the results, it could take some time ! Thank you
– lolveley
Nov 9 at 21:19












No worries - just edited the XAML as noticed an error. I'll also mention that the xceed WPF Toolkit (free version) includes a CheckComboBox, which you may want to consider (if you're not already using it). Save reinventing the wheel.
– Simon Evans
Nov 9 at 21:40




No worries - just edited the XAML as noticed an error. I'll also mention that the xceed WPF Toolkit (free version) includes a CheckComboBox, which you may want to consider (if you're not already using it). Save reinventing the wheel.
– Simon Evans
Nov 9 at 21:40












2 comments about my edit : a pair of tags was missing (<checkbox. isChecked> and its closing sibling) and the first value, value[0], was unset. I think the initialization has problems but I can't figure out where.
– lolveley
Nov 10 at 12:29




2 comments about my edit : a pair of tags was missing (<checkbox. isChecked> and its closing sibling) and the first value, value[0], was unset. I think the initialization has problems but I can't figure out where.
– lolveley
Nov 10 at 12:29












for the provided component : now that I spent a lot of time to make it work, with your aid, I am avid to succeed in completing the job !
– lolveley
Nov 10 at 12:33




for the provided component : now that I spent a lot of time to make it work, with your aid, I am avid to succeed in completing the job !
– lolveley
Nov 10 at 12:33












I have suggested some edits in the answer.
– Simon Evans
Nov 10 at 14:00




I have suggested some edits in the answer.
– Simon Evans
Nov 10 at 14:00


















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53232081%2fbind-a-comboboxitem-as-a-checkbox-to-its-presence-in-a-list%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Full-time equivalent

さくらももこ

13 indicted, 8 arrested in Calif. drug cartel investigation