Reputation: 103
I need to bind a List<Key>
to TextBox
. I've written a converter which converts from List<Key>
to string (the ConvertBack
method just throws an exception - it isn't used). Problem is that when I try to use this converter, it shows me an error: The TypeConverter for "IValueConverter" does not support converting from a string. It appears that the problem is caused because it's trying to convert string
from TextBox
to List<Key>,
but I don't want to do that (user won't "write" to this TextBox
). I've already thought about using something else than TextBox
- perhaps TextBlock
which I think would solve the problem, but I'd like to use TextBox
for some other reasons.
My property I want to bind:
public partial class Settings : Window
{
public List<Key> hotkeyCapture_keys { get; set; }
...
Converter:
class ListKeyToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Join(" + ", (List<Key>)value);
}
...
And TextBox:
<TextBox ... Text="{Binding hotkeyCapture_keys, Converter=ListKeyToStringConverter}" />
When try to Build it, the app immediately shuts down with "XamlParseException occured".
Can anyone tell me how to solve this problem?
Thanks
Upvotes: 0
Views: 786
Reputation: 2741
change your return value in converter to
return String.Join(" + ", ((List<Key>)value).ToArray());
you can have a look at WPF textblock binding with List<string>
Upvotes: 0
Reputation: 5163
Not sure if this is really something you want to do. If you want a read-only TextBox
there are other ways of doing so out there already; one that you mentioned, another being RichTextBox
. But I'll assume you know what you want.
You'll first want to use this in your Convert
(don't forget to add using System.Linq;
):
return string.Join(" + ", ((List<Key>)value).Select(x=> x.Name));
//where Name is a public property in type Key
Secondly--bingo, TextBox.Text
binds Mode=TwoWay
by default. You can change that to OneWay
or OneTime
:
<TextBox ... Text="{Binding hotkeyCapture_keys, Mode=OneTime, Converter=ListKeyToStringConverter}" />
Also, you're throwing an exception. Something has to handle that exception. Nothing is. Instead of throwing an exception in ConvertBack
, just call return null;
Upvotes: 1