【发布时间】:2015-09-15 00:50:43
【问题描述】:
在这段代码中:
<ListBox
x:Name="DataList1"
xmlns:local="clr-namespace:xaml_binding_commands"
>
<ListBox.Resources>
<local:CommandUp x:Key="CommandUp1"></local:CommandUp>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox
Text="{Binding Height,Mode=TwoWay,StringFormat=00\{0:d\}}"
InputScope="Number"/>
<RepeatButton
Content="+"
Command="{StaticResource CommandUp1}"
CommandParameter="{Binding }"
/>
<TextBox
Text="{Binding Weight,Mode=TwoWay}"
InputScope="Number"/>
<RepeatButton
Content="+"
Command="{StaticResource CommandUp1}"
CommandParameter="{Binding Weight}"
/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
还有这个
namespace xaml_binding_commands
{
public class CommandUp : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (parameter is Entry)
{
Entry EntryToUp = (Entry)parameter;
EntryToUp.Height +=1; // no worky, which field to increment?!
}
if (parameter is Int32)
{
Int32 EntryFieldToUp = (Int32)parameter;
EntryFieldToUp += 1; // no worky
}
}
}
public class Entry : INotifyPropertyChanged
{
private Int32 _Height;
public Int32 Height
{
get { return _Height; }
set { _Height = value; PropChange("Height"); }
}
private Int32 _Weight;
public Int32 Weight
{
get { return _Weight; }
set { _Weight = value; PropChange("Weight"); }
}
private void PropChange(String PropName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(PropName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private ObservableCollection<Entry> _People = new ObservableCollection<Entry>();
public ObservableCollection<Entry> People
{
get { return _People; }
set { _People = value; }
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
DataList1.ItemsSource = People;
People.Add( new Entry() { Height=67, Weight=118 } );
}
}
}
我可以通过引用传递文本框绑定的字段吗?如果我将整个类(一个条目)传递给 CommandParameter,以便它可以操作和递增,我无法知道是哪一组 TextBoxes 和 Buttons 导致了 Command.Execute。如果我传递与 TextBox 绑定的相同内容,即单独传递:Weight,Height,则 Command.Execute 无法影响输入。通常我会 PassByReference 并且我的 Int32 会被装箱,而我的一般操作函数可以对 by-ref 参数进行操作。我可以在 XAML 中以某种方式执行此操作吗?
【问题讨论】:
-
您可以使用绑定属性的设置器。可选用 UpdateSrcTrigger=PropertyChanged。
-
@HenkHolterman 使用 setter 做什么?我已经在通知场景中使用了设置器,并且该部分工作正常。问题出在 ICommand 中。我也不清楚 UpdateSourceTrigger 将如何影响我的 ICommand 问题。
标签: c# wpf xaml data-binding pass-by-reference