Reputation: 3442
I simply want to pass parameter to the control. But it threw error "Input string was not in a correct format." Why?* *
Xaml
<Views:SomeView SecurityId="abc"></Views:SomeView>
Model:
class Data
{
public string Case { get; set; }
public Data(int _input)
{
if (_input==1)
{
Case = "First";
}
else
{
Case = "Second";
}
}
}
ViewModel:
class DataViewModel
{
public string GetData
{
get
{
return D.Case;
}
set
{
D.Case = value;
}
}
public Data D;
public DataViewModel(string i)
{
D = new Data(Convert.ToInt16(i));
}
}
MainWindow
public partial class SomeView : UserControl
{
public string SecurityId
{
get
{
return (string)GetValue(SecurityIdProperty);
}
set { SetValue(SecurityIdProperty, value); }
}
public static readonly DependencyProperty
SecurityIdProperty =
DependencyProperty.Register("SecurityId",
typeof(string), typeof(SomeView),
new PropertyMetadata(""));
public SomeView()
{
DataContext = new DataViewModel(SecurityId);
InitializeComponent();
}
}
Upvotes: 2
Views: 1427
Reputation: 77285
You never listened for changes.
You construct your DataViewModel
with the value that SecurityId
has at the time of the constructor call. Which is the default ""
. Then you change the value to "abc"
through XAML. But that change is not transported anywhere. It happens and nobody cares. The construction of your DataViewModel
is already done.
Do you want to listen to changes? I cannot tell. You will need to register a change handler for your dependency property.
In your PropertyMetaData you can pass a changed event handler as second parameter, for example a static method:
public static readonly DependencyProperty
SecurityIdProperty =
DependencyProperty.Register("SecurityId",
typeof(string), typeof(SomeView),
new PropertyMetadata("", new PropertyChangedCallback(MyValueChanged)));
You can then have a method to handle changes:
private static void MyValueChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
{
// react on changes here
}
It's not an attached property by the way. It's a normal dependency property.
Upvotes: 3
Reputation: 1973
This is because, you are trying to parse "abc" as integer, but you are not handling exceptions caused by ConvertTo.Int16() method.
Write DataViewModel constructor like,
public DataViewModel(string i)
{
int value = 0;
int.TryParse(i, out value); // TryParse handles the exception itself.
D = new Data(value);
}
Upvotes: 0