I wrote this code:
public class CustomData
{
public int F1 { get; set; }
public int F2 { get; set; }
public string F3 { get; set; }
}
public class RetrievCustomData : List<CustomData>
{
public RetrievCustomData GetSome(int i)
{
for (int j = 0; j < i; j++)
{
CustomData cd = new CustomData();
Random rnd = new Random();
cd.F1 = j;
cd.F2 = rnd.Next(i);
cd.F3 = "nima";
this.Add(cd);
}
return this;
}
}
and:
<Window.Resources>
<ObjectDataProvider x:Key="ADUsers" ObjectType="{x:Type src:RetrievCustomData}"
MethodName="GetSome">
<ObjectDataProvider.MethodParameters>
<sys:Int32>20</sys:Int32>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
I want to pass my parameter (here is 20) value dynamically (get fron user). How I can do this?
Supply some default value to the DataProvider so that it s already set up and bound to your UI.
Accept a value from user at runtime and then supply that to the data provider using FindResource call and refresh...
var myValue = GetFromUser();
((ObjectDataProvider)this.FindResource("ADUsers")).MethodParameters.Clear();
((ObjectDataProvider)this.FindResource("ADUsers")).MethodParameters.Add(myValue);
((ObjectDataProvider )this.FindResource("ADUsers")).Refresh();
Or another tricky way is to OneWayToSource binding with MethodParameters...
<TextBox x:Name="UserInput">
<TextBox.Text>
<Binding Source="{StaticResource ADUsers}"
Path="MethodParameters[0]"
BindsDirectlyToSource="True"
Mode="OneWayToSource">
</Binding>
</TextBox.Text>
</TextBox>
But for this to work your TextBox Text (string) must be matched to the type of the parameter which sadly in our case is integer. In order to fix that create a converter that will take care of this issue.
public class IntToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int intValue = 0;
string strText = value?.ToString();
if (!string.IsNullOrEmpty(strText))
{
intValue = int.Parse(strText);
}
return intValue;
}
}