Вы можете связать свою кнопку, используя PlacementTarget
<Button BorderThickness="1" Visibility="Visible" Command="{*..and now I want to bind my command...*}" DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"/>
. Позже в коде вам нужно указать тег, он ищет окно, но вы можете изменить anecestorType.
<TextBox Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
Конечно, в вашей ViewModel (DataContext) вы должны указать правильную команду.
You are searching for a multimap, and indeed both commons-collections and Guava have several implementations for that. Multimaps allow for multiple keys by maintaining a collection of values per key, i.e. you can put a single object into the map, but you retrieve a collection.
If you can use Java 5, I would prefer Guava's Multimap
as it is generics-aware.
Никакое воображение не освобождает требуемый. Карты определяются уникальным ключом, не изгибайте их, используйте список. Потоки являются могущественными.
import java.util.AbstractMap.SimpleImmutableEntry;
List<SimpleImmutableEntry<String, String>> nameToLocationMap = Arrays.asList(
new SimpleImmutableEntry<>("A", "A1"),
new SimpleImmutableEntry<>("A", "A2"),
new SimpleImmutableEntry<>("B", "B1"),
new SimpleImmutableEntry<>("B", "B1"),
);
И вот именно. Примеры использования:
List<String> allBsLocations = nameToLocationMap.stream()
.filter(x -> x.getKey().equals("B"))
.map(x -> x.getValue())
.collect(Collectors.toList());
nameToLocationMap.stream().forEach(x ->
do stuff with: x.getKey()...x.getValue()...
Если есть дубликаты keys, то ключ может соответствовать более чем одному значению. Очевидное решение - сопоставить ключ со списком этих значений.
Например, в Python:
map = dict()
map["driver"] = list()
map["driver"].append("john")
map["driver"].append("mike")
print map["driver"] # It shows john and mike
print map["driver"][0] # It shows john
print map["driver"][1] # It shows mike
для полноты: Apache Commons Collections также имеет MultiMap . Обратной стороной, конечно же, является то, что Apache Commons не использует Generics.
Could you also explain the context for which you are trying to implement a map with duplicate keys? I am sure there could be a better solution. Maps are intended to keep unique keys for good reason. Though if you really wanted to do it; you can always extend the class write a simple custom map class which has a collision mitigation function and would enable you to keep multiple entries with same keys.
Note: You must implement collision mitigation function such that, colliding keys are converted to unique set "always". Something simple like, appending key with object hashcode or something?
If you want iterate about a list of key-value-pairs (as you wrote in the comment), then a List or an array should be better. First combine your keys and values:
public class Pair
{
public Class1 key;
public Class2 value;
public Pair(Class1 key, Class2 value)
{
this.key = key;
this.value = value;
}
}
Replace Class1 and Class2 with the types you want to use for keys and values.
Now you can put them into an array or a list and iterate over them:
Pair[] pairs = new Pair[10];
...
for (Pair pair : pairs)
{
...
}
You could simply pass an array of values for the value in a regular HashMap, thus simulating duplicate keys, and it would be up to you to decide what data to use.
You may also just use a MultiMap, although I do not like the idea of duplicate keys myself.