在我的程序中,我有TextBlock
绑定到数据模型中的属性值。我想将此TextBlock
更改为TextBox
,以便它可以编辑,但仍希望将文本绑定到它。问题是,当我将TextBlock
更改为TextBox
时,我的绑定不起作用,TextBox
显示为空白。
我绑定的属性是我在程序中的自定义类。
这是财产:
//Property for Display Name
public MultiItemString DisplayName {}
这是MultiItemString
类:
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));
}
}
我的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" />
如何将此属性绑定到TextBox
作为文本值,就像我使用TextBlock
一样?
答案 0 :(得分:2)
这应该有效:
<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" />
并且,将Value属性更新为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;
}
}