How to pass ObjectDataProvider.MethodParameters value dynamically at runtime

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 the value of my parameter (here 20) dynamically (get from the user). How can i do this?

+5
source share
1 answer
  • Set some default value for the DataProvider so that it is already configured and bound to your user interface.

  • Take a value from the user at runtime, and then pass it to the data provider by calling and updating FindResource ...

            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 to associate OneWayToSource with MethodParameters ...

    <TextBox x:Name="UserInput">  
      <TextBox.Text> 
                <Binding Source="{StaticResource ADUsers}"   
                         Path="MethodParameters[0]"   
                         BindsDirectlyToSource="True" 
                         Mode="OneWayToSource">  
                </Binding> 
      </TextBox.Text> 
    </TextBox>

TextBox Text () , , , . , , .

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;
    } 
}
+5

All Articles