在可绑定命令中包装UserControl功能

时间:2014-11-03 14:18:28

标签: c# wpf icommand routedcommand

如果你觉得这个问题太愚蠢,请不要再谴责我了。请听我说:

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

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

    我希望DependencyProperty中的MyControl名为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的消费者将ExportDataProperty绑定到ViewModel公开的ICommand,该怎么办?我不想让这种情况发生。

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

1 个答案:

答案 0 :(得分: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.
    }
    ...
}

XAML

<local:MyControl x:Name="myControl" />
<Button Command="{Binding ElementName=myControl, Path=ExportData" />