Reputation: 1088
What do I have to code to initialize a object with a non-primitive property.
Like when having the following Model and ViewModel:
public class ListEntry
{
public int ID { get; set; }
public string IP { get; set; }
}
public class ViewModel
{
public ObservableCollection<ListEntry> ListEntries { get; set; }
}
then I can code this XAML DesignData:
<nc:ViewModel
xmlns:nc="clr-namespace:NetWorkItOut.NetworkClasses">
<nc:ViewModel.ListEntries>
<nc:ListEntry ID="1" IP="192.168.178.1" />
<nc:ListEntry ID="2" IP="192.168.178.255" />
</nc:ViewModel.ListEntries>
</nc:ViewModel>
and everything works. But when replacing
public string IP { get; set; }
with
public IPAddress IP { get; set; }
this does not work (since IPaddress has no constructor that takes a string.
So how can I solve this? (Displaying the IP Value with the design data)
Upvotes: 0
Views: 71
Reputation: 128147
Create a TypeConverter
that converts from string
to IPAddress
:
using System.ComponentModel;
...
public class IPAddressConverter : TypeConverter
{
public override bool CanConvertFrom(
ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(
ITypeDescriptorContext context, CultureInfo culture, object value)
{
return IPAddress.Parse((string)value);
}
}
Register the TypeConverter
for the IP
property like this:
public class ListEntry
{
public int ID { get; set; }
[TypeConverter(typeof(IPAddressConverter))]
public IPAddress IP { get; set; }
}
Upvotes: 1
Reputation: 11399
A simple way is to wrap the IPAddress
with an additional string
property:
public IPAddress IP { get; set; }
public string StringIP
{
get
{
return IP.ToString();
}
set
{
IP = IPAddress.Parse(value);
}
}
Now you can use the wrapped property to set the IP:
<nc:ListEntry ID="2" StringIP="192.168.178.255" />
Upvotes: 1