0

如果您觉得这个问题太愚蠢,请不要阻止自己谴责我。请听我说:

  1. 我有一个自定义用户控件,我可以在其中随意添加任意数量的依赖属性。
  2. 该控件基本上是一个数据呈现控件(我将其称为 MyControl)。
  3. MyControl 有一个功能(读取方法),使其能够将呈现的数据保存在磁盘位置。

好的,现在这就是我想要的:

我想要一个DependencyPropertyinMyControl调用ExportDataProperty,它将为 xaml 中的按钮包装此功能以绑定到它。这是一些粗略的代码来解释它:

public class MyControl:Control
{

    /// <summary>
    /// <see cref="DependencyProperty"/> for the command that is fired to export the data
    /// </summary>
    public static readonly DependencyProperty ExportDataProperty = DependencyProperty.Register("ExportData", typeof(ICommand), typeof(MyControl), new UIPropertyMetadata(null));

    /// <summary>
    /// Gets or sets the instance of <see cref="ICommand"/> that executes the functionality of exporting.
    /// Please note that this is a synchronous call. It is advised NOT to call this for very big datasets.
    /// </summary>
    public ICommand ExportData
    {
        get { return GetValue(ExportDataProperty) as RoutedCommand; }
        set { SetValue(ExportDataProperty, value); }
    }

    /// <summary>
    /// How do I involve myself with the above command??
    /// how, How, HOw, HOW??
    /// </summary>
    private void ExportMethod()
    {
       string filename = GetFilenameByMagic();
       //Blah blah code to save at filename location.
    }

    private string GetFilenameByMagic()
    {
         return Magic.ReturnFilename();
    }    
}

我想如何使用它?

<Window x:Name="AVeryBigWindow">
  <Window.Resources>
    <ResourceDictionary Source = "pack://application:,,,/FoolsFactory; component/Resources/FunnyColors.xaml"/>
  <Window.Resources>
  <StackPanel>
     <Button Command={Binding ExportData ElementName=myFunnyControl} Content="Click to Export"/>
     <controls:MyControl x:Name="myFunnyControl"/>
  </StackPanel>
</Window >

我不知道如何包装ExportMethod里面的命令?

我担心的另一个问题是:如果消费者将MyControl绑定ExportDataPropertyICommandViewModel 公开的对象上怎么办?我不想让这种事情发生。

我以错误的方式接近它吗?任何帮助将不胜感激。

4

1 回答 1

0

您可以在控件中设置命令,然后通过绑定将其与您的按钮一起使用。

CS

public class MyControl:Control
{
    ...
    public MyControl() 
    {
        ExportData = new DelegateCommand(ExportMethod);
    }

    private void ExportMethod()
    {
       string filename = GetFilenameByMagic();
       //Blah blah code to save at filename location.
    }
    ...
}

xml

<local:MyControl x:Name="myControl" />
<Button Command="{Binding ElementName=myControl, Path=ExportData" />
于 2014-11-05T08:18:06.520 回答