Reputation: 1808
In my program I have a TextBlock
that is bound to a property value in a data model. I would like to change this TextBlock
to a TextBox
so that it is editable, but would still like to bind text to it. The problem is, when I change the TextBlock
to a TextBox
, my binding does not work, and the TextBox
appears blank.
The property that I am binding to is of a custom class that I have in my program.
This is the property:
//Property for Display Name
public MultiItemString DisplayName {}
This is the MultiItemString
class:
public class MultiItemString : INotifyPropertyChanged
{
private readonly string[] _keys;
private readonly MultiItemString[] _nestedItems;
readonly bool _resourceKey;
private readonly bool _nestedMultiItemStrings;
public MultiItemString(IEnumerable<string> keys, bool resourceKey = true)
{
_keys = keys.ToArray();
_resourceKey = resourceKey;
LanguageChange.LanguageChagned += (sender, args) => RaisePropertyChanged("");
}
public MultiItemString(IEnumerable<MultiItemString> nestedItems)
{
_nestedItems = nestedItems.ToArray();
foreach (var multiItemString in _nestedItems)
{
multiItemString.PropertyChanged += (s, e) => RaisePropertyChanged("Value");
}
_nestedMultiItemStrings = true;
}
public string Key
{
get
{
if (_keys != null && _keys.Length != 0) return _keys[0];
return null;
}
}
public string Value
{
get
{
var sb = new StringBuilder();
if (_nestedMultiItemStrings)
{
foreach (var MultiItemString in _nestedItems)
{
sb.Append(MultiItemString.Value);
}
}
else
{
foreach (var key in _keys)
{
sb.Append(_resourceKey ? (string)Application.Current.Resources[key] : key);
}
}
return sb.ToString();
}
}
public override string ToString()
{
return Value;
}
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string propertyName)
{
var temp = PropertyChanged;
if (temp != null)
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
My xaml:
<TextBox Text="{Binding Model.DisplayName}" Height="28" HorizontalAlignment="Left" Name="title_TB" VerticalAlignment="Top" Width="Auto" FontWeight="Bold" FontSize="14" Margin="5,2,0,0" />
How can I bind this property to a TextBox
as it's text value, just like I do with TextBlock
?
Upvotes: 0
Views: 88
Reputation: 17509
This should work:
<TextBox Text="{Binding Model.DisplayName.Value}" Height="28" HorizontalAlignment="Left" Name="title_TB" VerticalAlignment="Top" Width="Auto" FontWeight="Bold" FontSize="14" Margin="5,2,0,0" />
And, update Value property to have setter:
private string _thisShouldBeAValidField ;
public string Value
{
get
{
if(_thisShouldBeAValidField!=null) return _thisShouldBeAValidField;
var sb = new StringBuilder();
if (_nestedMultiItemStrings)
{
foreach (var MultiItemString in _nestedItems)
{
sb.Append(MultiItemString.Value);
}
}
else
{
foreach (var key in _keys)
{
sb.Append(_resourceKey ? (string)Application.Current.Resources[key] : key);
}
}
return sb.ToString();
}
set{
_thisShouldBeAValidField = value;
}
}
Upvotes: 2