【发布时间】:2016-01-25 13:09:14
【问题描述】:
我尝试将 mycollection 绑定到 wpf:
private ObservableCollection<MyClass> _coll;
public ObservableCollection<MyClass> Coll
{
get
{
if (_coll == null)
_coll = new ObservableCollection<MyClass>();
return _coll;
}
set
{
_coll = value;
}
}
MyClass:
class MyClass
{
int Id;
String Name1;
String Name2;
}
在 WPF:
<ListBox Grid.Row="1" x:Name="lbKey" BorderBrush="Gray"
ItemsSource="{Binding Path=Coll}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
HorizontalContentAlignment="Stretch"
ItemContainerStyle="{StaticResource ResourceKey=lbStyle}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="LightGray" Background="WhiteSmoke"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<TextBlock Text="{Binding}" TextWrapping="Wrap" Margin="2"
Background="Transparent"
HorizontalAlignment="Stretch"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
但是,当我运行程序时,会看到类似 Id.ToString(); 所以,我必须重写 ToString() 方法,但我不能改变 MyClass 方法。
我创建了扩展方法:
namespace Some.Name.Space
{
public static class MyClassExtensions
{
public static string ToString(this MyClass my)
{
return String.Format("{0} {1}"my.Name1,my.Name2);
}
}
}
但这对我没有帮助:我看到我的网格字符串是这样的:1,2 等等。
你能告诉我,如何在扩展方法中重写 ToString 方法并将其绑定到 WPF 中。
【问题讨论】:
-
另请注意,您的 MyClass 字段是私有的,您的扩展方法甚至不会编译,因为这些字段是私有的,您无法访问它们,因此您无法覆盖 ToString() 以返回格式化的除非你诉诸反射,否则你说你想要的字符串。
标签: c# wpf data-binding extension-methods