如果你觉得这个问题太愚蠢,请不要再谴责我了。请听我说:
我希望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
,该怎么办?我不想让这种情况发生。
我接近错误的方式吗?任何帮助将不胜感激。
答案 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" />